﻿//控制台
function consoleLog(content) {
    try {
        window.console && console.log(content);
    } catch (e) {

    }
}
//加载旋转动画
function loadingAnimation() {
    var loadingLayer = layer.load(1, {
        shade: [0.3, '#fff'] //0.3透明度的白色背景
    });
    return loadingLayer;
}


//选择题与判断题答案选择
function selectAnswer() {

    var standarAnswer = $(".xuanxiang-group a");
    standarAnswer.unbind("click").click(function () {
        var collectiveA = $(this).parent().children("a");
        //单选题和判断题只能选择一个答案
        if (index == 0 || index == 3) {
            collectiveA.removeClass("selected");
            $(this).addClass("selected");
        }

        //多选题必须有多个答案
        if (index == 1) {
            $(this).toggleClass("selected");
        }
    })
}

//试卷目录管理
function catalogueManage() {

    $("#manageSection").remove();
    //生成试卷目录管理弹窗目录
    generateCatalogueItems();

    //试卷目录管理 上下移动与删除
    catalogueEvent();

    //添加新目录
    $(".open-content div.col-content .col-title-add").click(function () {

        //添加新栏目
        //最多添加20个栏目
        if ($(".question-review").length < 20) {
            addNewColumn(true);
        }
        else {
            layer.msg("最多添加20个栏目");
        }

    })
}

//生成试卷目录管理弹窗目录
function generateCatalogueItems() {
    var sectionsStr = "";
    var sections = $(".question-review .question-title");
    var sectionsLength = $(".question-review .question-title").length;

    //生成章节字符串
    if (examPaperForm == 1) {
        for (var i = 0; i < sectionsLength; i++) {
            sectionsStr += '<div class="col-content sectionItem clearfix" data-sectionguid="' + sections.eq(i).attr("data-sectionguid") + '" data-sequence="' + (i + 1) + '">' +
                                        '<div class="col-title" >' +
                                            '<div class="type">栏目' + /*Arabia_To_SimplifiedChinese(i + 1)*/parseInt(i + 1) + '</div>' +
                                            '<div class="col-name col-name-fixed">' + sections.eq(i).children().children(".sectionTitle").html() + '</div>' +
                                            '<input type="text" maxlength="20" class="col-name input_item input-block-hide col-name-wide">' +
                                        '</div>' +
                                        '<div class="col-menu clearfix">' +
                                            '<a class="down" href="javascript:void(0)"></a>' +
                                            '<a class="up" href="javascript:void(0)"></a>' +
                                            '<a class="close" href="javascript:void(0)"></a>' +
                                        '</div>' +
                                  '</div>';
        }
    }
    if (examPaperForm == 2) {
        for (var i = 0; i < sectionsLength; i++) {
            sectionsStr += '<div class="col-content sectionItem clearfix" data-sectionguid="' + sections.eq(i).attr("data-sectionguid") + '" data-sequence="' + (i + 1) + '">' +
                                '<div class="type">栏目' + parseInt(i + 1) + '</div>' +
                                '<div class="label-name">' + sections.eq(i).children().children(".randomTx").html().substring(1, 4) + '</div>' +
                                '<div class="col-title">' +
                                    '<div class="col-name">' + sections.eq(i).children().children(".sectionTitle").html() + '</div>' +
                                    '<input type="text" maxlength="20" class="col-name input_item input-block-hide col-name-wide">' +
                                '</div>' +
                                '<div class="col-menu"><a class="down" href="javascript:void(0)"></a><a class="up" href="javascript:void(0)"></a><a class="close" href="javascript:void(0)"></a></div>' +
                          '</div>';
        }
    }



    //页面层
    var layerControl = layer.open({
        type: 1,
        title: ["试卷栏目管理", "background-color: #ffc600; font-size: 18px; line-height: 42px; padding-left: 20px;"],
        skin: '', //加上边框 layui-layer-rim
        area: ['578px', 'auto'], //宽高
        content: '<div id="manageSection">' +
                    '<div class="open-content">' +
                        sectionsStr +
                        '<div class="col-content clearfix">' +
                            '<div class="col-title-add">添加新栏目</div>' +
                        '</div>' +
                    '</div>' +
                    '<div class="open-button">' +
                        '<div class="open-container clearfix"><a href="javascript:void(0)" class="cancel">取 消</a><a href="javascript:void(0)" class="save">保 存</a></div>' +
                    '</div>' +
                '</div>',
        cancel: function () {
            ////初始化拖动排序
            //initSortalbe();
            //// 调整章节样式
            //checkSection();
        }
    });
}

//试卷目录管理 上下移动与删除,保存和取消
function catalogueEvent() {

    var down = $(".open-content div.col-content .col-menu a.down");
    var up = $(".open-content div.col-content .col-menu a.up");
    var deleteIt = $(".open-content div.col-content .col-menu a.close");
    var cancel = $(".open-button div.open-container a.cancel");
    var save = $(".open-button div.open-container a.save");
    var editDiv = $(".open-content div.col-content .col-title div.col-name");
    var editInput = $(".open-content div.col-content .col-title input.col-name");

    //获取sectionguid字符串
    var titleBlock = $("#manageSection .sectionItem");
    var postObj = new Array();
    for (var i = 0; i < titleBlock.length; i++) {
        postObj.push(titleBlock.eq(i).attr("data-sectionguid"));
    }
    var originalSectionGuidStr = postObj.toString();
    postObj = null

    down.click(function () {

        var index = $(".open-content div.col-content .col-menu a.down").index($(this));
        var len = $(".open-content div.col-content .col-menu a.down").length;
        if (index + 1 != len) {

            //保持栏目序号不变
            $(this).parent().parent().next().children(".col-title").children(".type").html("栏目" + parseInt(index + 1));
            $(this).parent().siblings(".col-title").children(".type").html("栏目" + parseInt(index + 2));

            $(this).parent().parent().insertAfter($(this).parent().parent().next());

        }
        else {
            layer.tips('已到最后', $(".open-content div.col-content .col-menu a.down").eq(index), { tips: [2, '#f06150'] });
        }
    })

    up.click(function () {
        var index = $(".open-content div.col-content .col-menu a.up").index($(this));
        var len = $(".open-content div.col-content .col-menu a.up").length;
        if (index != 0) {
            //保持栏目序号不变
            $(this).parent().parent().prev().children(".col-title").children(".type").html("栏目" + parseInt(index + 1));
            $(this).parent().siblings(".col-title").children(".type").html("栏目" + parseInt(index));

            $(this).parent().parent().insertBefore($(this).parent().parent().prev());
        }
        else {
            layer.tips('已到最前', $(".open-content div.col-content .col-menu a.up").eq(index), { tips: [2, '#f06150'] });
        }
    })

    deleteIt.click(function () {
        //var index = $(".open-content div.col-content .col-menu a.close").index($(this));
        var sectionSeq = $(this).parents('.sectionItem').attr("data-sequence");
        var title = $(".question-review .question-title");
        //删除栏目、移动试题到新栏目
        deleteTitle(title.eq(sectionSeq - 1), true);
    })

    cancel.click(function () {
        layer.closeAll('page');
    })

    //保存
    save.click(function () {
        var titleBlock1 = $("#manageSection .sectionItem");
        var postObj1 = new Array();
        var reorderArray = new Array();
        for (var i = 0; i < titleBlock.length; i++) {
            postObj1.push(titleBlock1.eq(i).attr("data-sectionguid"));
            reorderArray.push(titleBlock1.eq(i).attr("data-sequence"));
        }
        var postStr = postObj1;

        currentStr = postObj1.toString();
        postObj1 = null;

        //当用户对栏目顺序有改动时       
        if (currentStr != originalSectionGuidStr) {
            var loadingLayer = loadingAnimation();
            $.ajax({
                type: "POST",
                url: DomainUrlHelper.InstituCenterAction + "api/apipaper/movesection?paperGuid=" + paperGuid,
                contentType: "application/json",

                dataType: "json",
                data: JSON.stringify(postStr),
                success: function (jsonResult) {
                    consoleLog(jsonResult);
                    if (jsonResult.ErrorCode == "E0006") {

                        var questionR = $(".question-review");

                        //根据移动结果，将页面章节和下面的试题重新排序
                        for (var j = 0; j < reorderArray.length; j++) {
                            questionR.parent().append(questionR.eq(reorderArray[j] - 1));
                        }

                        updateSectionOrder();

                        //页面试题重新排序
                        questionsReorder();

                        //刷新左侧标题
                        updateLeftCatalogue();

                        //初始化拖动排序
                        initSortalbe();
                        // 调整章节样式
                        checkSection();

                        layer.closeAll("page");
                        layer.close(loadingLayer);
                    }
                    else {
                        layer.close(loadingLayer);
                        layer.msg(jsonResult.ErrorCode);
                    }
                }
            });


        }
        else {

            //刷新左侧标题
            updateLeftCatalogue();

            //初始化拖动排序
            initSortalbe();
            // 调整章节样式
            checkSection();

            layer.closeAll("page");


        }


    })

    //在弹出框中编辑栏目标题
    var columnName;
    editDiv.click(function () {
        columnName = $(this).html();
        $(this).hide().siblings("input.col-name").show().val($.trim($(this).html()));
        editInput.focus();
    })
    //文本框失去焦点
    editInput.unbind("blur").blur(function () {
        var pointer = $(this);
        $(this).hide().siblings("div.col-name").show().html($.trim($(this).val()));

        if ($.trim($(this).val()) != "") {
            if ($(this).val() != columnName) {

                //验证栏目名是否含有特殊字符
                if (checkInput($(this).val())) {
                    var loadingLayer = loadingAnimation();
                    $.post(DomainUrlHelper.InstituCenterAction + "api/apipaper/editsection", {
                        sectionName: $(this).val(),
                        examPaperGUID: getPaperGuid(),
                        sectionGuid: $(this).parent().parent().attr("data-sectionguid")
                    }, function (data) {
                        consoleLog(data);
                        if (data.ErrorCode == "E0006") {
                            //questionInfo.sectionGUID = data.SectionGuid;

                            //修改右侧栏目名称
                            $(".question-review").eq(pointer.parent().parent().attr("data-sequence") - 1).children(".question-title").children(".question-title-content").children(".sectionTitle").html(pointer.val());

                            //刷新左侧标题
                            updateLeftCatalogue();
                        }
                        layer.close(loadingLayer);
                    })
                }
                else {
                    layer.msg("栏目名称不能包含特殊字符！");
                    pointer.parent().children(".col-name").html(columnName);
                }

            }
        }
        else {
            layer.msg("栏目名称不能为空！");
            $(this).siblings("div.col-name").html(columnName);
        }

    })

}


//添加新栏目 flag为真是从试题目录管理处添加目录，为假是直接添加目录
function addNewColumn(flag) {
    editArea.hide();
    generateColumn();
    displayTitleTool();//鼠标移动到章节标题栏上，编辑/删除/添加显隐

    var column = $(".question-review");
    var index = column.length;
    editTitle(column.eq(index - 1).find(".edit"), true, flag);

    //重新绑定编辑标题
    $(".small-icon-left .edit").unbind("click").click(function () {
        editTitle($(this), false, flag);
    });

    //绑定删除栏目、移动试题到新栏目
    deleteColumn();

    //在栏目上点击添加试题
    addQuestionOnColumn();


}


//计算当前试卷总分
function getAllSectionScore() {
    //获取当前栏目分数之和
    var sectionScore = $(".question-title .sectionScore");
    var currentScore = 0;
    for (var i = 0; i < sectionScore.length; i++) {
        currentScore += parseInt(sectionScore.eq(i).html());
    }
    return currentScore;
}

//设定试题分数
function setQuestionScore(plus, minus, score) {

    plus.click(function () {
        var str = $.trim(score.val());
        var value = parseInt(str);
        //当为填空题
        if (index == 2) {
            var count = $("#tab3 ul li.item").length;
            //if (((parseInt(score.val()) + 1) * count + getAllSectionScore()) < paperScore) {
            score.val((value + 1) + "分");
            $("#allBlankScore").html((value + 1) * count);
            //}
            //else {
            //    layer.tips('已到试卷分数上线！', score);
            //}
        }
            //不为填空题
        else {
            //if ((parseInt(score.val()) + getAllSectionScore()) < paperScore) {
            score.val((value + 1) + "分");
            $("#allBlankScore").html(value + 1);
            //}
            //else {
            //    layer.tips('已到试卷分数上线！', score);
            //}
        }
        $(this).blur();
    })

    //分数减1
    minus.click(function () {
        var str = $.trim(score.val());
        var value = parseInt(str);
        if (value > 0) {
            //当为填空题
            if (index == 2) {
                var count = $("#tab3 ul li.item").length;
                score.val((value - 1) + "分");
                $("#allBlankScore").html((value - 1) * count);
            } else {
                score.val((parseInt(score.val()) - 1) + "分");
                $("#allBlankScore").html(parseInt(score.val()));
            }
        }
        else {
            layer.tips('分数不能小于0！', score, { tips: [2, '#f06150'] });
        }
        $(this).blur();

    })

    //判断用户输入的分数的范围是否为合理的分数
    score.blur(function () {
        var str = $.trim($(this).val());
        var value = parseFloat(str);
        if (!validateNum(value) || value < 0) {
            layer.tips('分数输入不合理', score, { tips: [2, '#f06150'] });
            score.val("0分");
        }
        else {
            if (index == 2) {
                $("#allBlankScore").html($("#tab3 ul .editorItem").length * parseInt(score.val()));
            }
        }
    })

}

//批量设定试题分数 value是当前异步返回的分数,isSingle为真表示单独一题修改分数，为假表示批量修改
function setColloumQuestionScore(plus, minus, score, isSingle) {

    plus.click(function () {
        var a = $(this).siblings(".score");
        a.val(parseInt(a.val()) + 1);
        var counts = parseInt($(this).parent().parent().parent().attr("data-blank-count"));//填空题的空数，其他为1；
        if (!isSingle) {
            var sectionOrder = $("#setScore-columns").val();
            var questionOrder = parseInt($(this).parent().parent().siblings(".tigan").children(".th").text()) - 1;
            UpdatePaperScoreParamEntity.SectionScoreParamEntitys[sectionOrder].QuestionScoreParamEntitys[questionOrder].QuestionScore = parseInt(UpdatePaperScoreParamEntity.SectionScoreParamEntitys[sectionOrder].QuestionScoreParamEntitys[questionOrder].QuestionScore) + 1 * counts;
            paperData.PaperInfoEntity.SectionList[sectionOrder].QuestionList[questionOrder].QuestionScore = UpdatePaperScoreParamEntity.SectionScoreParamEntitys[sectionOrder].QuestionScoreParamEntitys[questionOrder].QuestionScore;
            $("#popCurrentSectionScore").html(parseInt($("#popCurrentSectionScore").html()) + 1 * counts); //弹出框 当前分数加1

        }
        $(this).blur();

    })

    //分数减1
    minus.click(function () {
        var s = $(this).siblings(".score");
        if (parseInt(s.val()) > 0) {
            s.val((parseInt(s.val()) - 1));
            var counts = parseInt($(this).parent().parent().parent().attr("data-blank-count"));//填空题的空数，其他为1；
            if (!isSingle) {
                var sectionOrder = $("#setScore-columns").val();
                var questionOrder = parseInt($(this).parent().parent().siblings(".tigan").children(".th").text()) - 1;
                UpdatePaperScoreParamEntity.SectionScoreParamEntitys[sectionOrder].QuestionScoreParamEntitys[questionOrder].QuestionScore = parseInt(UpdatePaperScoreParamEntity.SectionScoreParamEntitys[sectionOrder].QuestionScoreParamEntitys[questionOrder].QuestionScore) - 1 * counts;
                paperData.PaperInfoEntity.SectionList[sectionOrder].QuestionList[questionOrder].QuestionScore = UpdatePaperScoreParamEntity.SectionScoreParamEntitys[sectionOrder].QuestionScoreParamEntitys[questionOrder].QuestionScore;
                $("#popCurrentSectionScore").html(parseInt($("#popCurrentSectionScore").html()) - 1 * counts); //弹出框 当前分数减1
            }
        }
        $(this).blur();

    })

    score.focus(function () {
        var counts = parseInt($(this).parent().parent().parent().attr("data-blank-count"));//填空题的空数，其他为1；

        $("#popCurrentSectionScore").html(parseInt($("#popCurrentSectionScore").html()) - parseFloat($.trim($(this).val())) * counts);
    })

    //判断用户输入的分数的范围是否为合理的分数
    score.blur(function () {
        var str = $.trim($(this).val());
        var value = parseFloat(str);
        if (!validateNum(value) || value < 0) {
            $(this).val(0);
        }
        else {
            var sectionOrder = $("#setScore-columns").val();
            var questionOrder = parseInt($(this).parent().parent().siblings(".tigan").children(".th").text()) - 1;
            var counts = parseInt($(this).parent().parent().parent().attr("data-blank-count"));//填空题的空数，其他为1；
            if (!isSingle) {
                UpdatePaperScoreParamEntity.SectionScoreParamEntitys[sectionOrder].QuestionScoreParamEntitys[questionOrder].QuestionScore = value * counts;
                paperData.PaperInfoEntity.SectionList[sectionOrder].QuestionList[questionOrder].QuestionScore = UpdatePaperScoreParamEntity.SectionScoreParamEntitys[sectionOrder].QuestionScoreParamEntitys[questionOrder].QuestionScore;
            }
            $("#popCurrentSectionScore").html(parseInt($("#popCurrentSectionScore").html()) + value * counts); //弹出框 当前分数加1
        }
    })
}

//获取试卷ID
function getPaperGuid() {
    if (!paperGuid) {
        paperGuid = $("#hPaperGuid").val();
    }
    return paperGuid;
}

//获取试卷总分数
function getPaperScore() {
    if (!paperScore) {
        paperScore = $("#hPaperScore").val();
    }
    return paperScore;
}

//编辑器与文本框切换
var sameInput = -1;//通过它来判断用户是否点击的同一个文本框
function toggleEditor() {

    $("#tiganInfo, #jianda, .option ul li.item .optionInput, #explanation .optionInput").unbind("click").click(function () {
        var loadingLayer = loadingAnimation();
        if (sameInput == -1 || sameInput == $("#tiganInfo, #jianda, .option ul li.item .optionInput, #explanation .optionInput").index($(this))) {
            sameInput = $("#tiganInfo, #jianda, .option ul li.item .optionInput, #explanation .optionInput").index($(this));
            //获取点击的文本框中的内容
            var value = unescape($.trim($(this).html()));
            $(this).hide();
            $(this).parent().append(myEditor);
            //myEditor.slideDown(time500);
            myEditor.show();

            if (value) {
                //向编辑器中插入内容
                setTimeout(function () {
                    ue.execCommand('insertHtml', value);
                    layer.close(loadingLayer);
                }, 700);
            }
            else {
                layer.close(loadingLayer);
            }

        }
        else {
            //将编辑器中的数据添加到文本框中
            myEditor.hide();
            myEditor.siblings(".optionInput").html(getPlainTxt());
            $("#tiganInfo, #jianda, .option ul li.item .optionInput, #explanation .optionInput").show();
            //获取点击的文本框中的内容
            var value = unescape($.trim($(this).html()));
            $(this).hide();
            $(this).parent().append(myEditor);
            myEditor.show();

            if (value) {
                //向编辑器中插入内容
                setTimeout(function () {
                    ue.execCommand('insertHtml', value);
                    layer.close(loadingLayer);
                }, 700);
            }
            else {
                layer.close(loadingLayer);
            }
            sameInput = $("#tiganInfo, #jianda, .option ul li.item .optionInput, #explanation .optionInput").index($(this));
        }

        //置空编辑器
        ue.execCommand('insertHtml', "");
        //setTimeout(function () {
        //    ue.execCommand('insertHtml', "");
        //}, 1000);
    })

}
//编辑器与文本框切换
function toggleUMEditor() {

    $("#tiganInfo, #jianda, .option ul li.item .optionInput, #explanation .optionInput").unbind("click").click(function () {
        var loadingLayer = loadingAnimation();
        if (sameInput == -1 || sameInput == $("#tiganInfo, #jianda, .option ul li.item .optionInput, #explanation .optionInput").index($(this))) {
            sameInput = $("#tiganInfo, #jianda, .option ul li.item .optionInput, #explanation .optionInput").index($(this));
            //获取点击的文本框中的内容
            var value = unescape($.trim($(this).html()));
            $(this).hide();
            $(this).parent().append($('.edui-container'));
            ume.setContent("<p></p>");

            //myEditor.slideDown(time500);
            $(this).siblings('.edui-container').show();
            myEditor.show();
            if (value) {
                //向编辑器中插入内容
                ume.setContent(value);
                layer.close(loadingLayer);
            }
            else {
                layer.close(loadingLayer);
            }
            editorInitialized = true;
        }
        else {
            //将编辑器中的数据添加到文本框中
            if (editorInitialized) {
                myEditor.parents('.edui-container').siblings(".optionInput").html(getUMEditorContent());
            }
            ume.setContent("<p></p>");

            $("#tiganInfo, #jianda, .option ul li.item .optionInput, #explanation .optionInput").show();
            //获取点击的文本框中的内容
            var value = unescape($.trim($(this).html()));
            $(this).hide();
            $(this).parent().append(myEditor.parents('.edui-container'));
            $(this).siblings('.edui-container').show();
            myEditor.show();
            if (value) {
                //向编辑器中插入内容
                ume.setContent(value);
                layer.close(loadingLayer);
            }
            else {
                layer.close(loadingLayer);
            }
            sameInput = $("#tiganInfo, #jianda, .option ul li.item .optionInput, #explanation .optionInput").index($(this));
            editorInitialized = true;
        }
        ume.focus();
    })

}

//设定选择题选项数目
function setOptionQuestionCount(parent, count) {
    //限制添加选项数目
    var currentCount = parent.children("li.item").length;
    if (currentCount < count) {
        if (index == 2) { //填空题答案不再用编辑器   -lyw
            var li = parent.children("li.item").last().clone(false);
            var editorInput = li.children("input");
            editorInput.val("");
            li.find("ul").html("").removeClass().addClass("tiankong_ul");

            var editorSpan = li.children("span");
            editorSpan.text("空" + (currentCount + 1));
            li.insertBefore(parent.find(".other-function4"));
            AddTagitEvent(li);           
            $("#allBlankScore").html(parseInt(score.val()) * (parent.children("li.item").length));
            if (parent.children("li.item").length > 1) {
                parent.children("li.other-function4").show();
            }
        }
        else {
            var li = parent.children("li.item").last().clone(true);
            var editorDiv = li.children(".editorDiv");
            if (editorDiv.children("#editor").length) {
                editorDiv.children("#editor").remove();
                editorDiv.children(".optionInput").show();
            } else if (editorDiv.children(".edui-container").length) {
                editorDiv.children(".edui-container").remove();
                editorDiv.children(".optionInput").show();
            }
            li.insertBefore(parent.children().last());
            editorDiv.children(".optionInput").html("");
            optionsReorder(parent.children("li.item"));

            //添加答案
            addAnswer(parent);

            //绑定答案选择事件
            selectAnswer();
        }
    }
    else {
        layer.msg('选项已超出上限！');
    }
}

//增加答案选项 pointer为当前题型的增加或者删除指针
function addAnswer(pointer) {
    var answers = pointer.siblings(".right-xuanxiang").children(".xuanxiang-group");
    var len = answers.children("a").length;
    var letter = String.fromCharCode(65 + len);
    var newA = '<a href="javascript:void(0)">' + letter + '</a>';
    answers.append(newA);

}

//选择题 添加选项与删除选项
function optionAddAndDelete() {
    //选择题添加选项
    $(".other-function a.danxuan-addtxt").unbind("click").click(function () {
        var ul = $(this).parent().parent();
        //当为填空题
        if (index == 2) {
            var count = $("#tab3 ul li.item").length;
            //if (((parseInt(score.val())) * (count + 1) + getAllSectionScore()) <= paperScore) {
            setOptionQuestionCount(ul, 50);

            //}
            //else {
            //    layer.tips("每空总分之和将超过试卷总分", score);
            //}

        }
            //不为填空题
        else {
            setOptionQuestionCount(ul, 26);
        }
        //增减答案选项


    })
}

function DeleteOption(abcd) {
    var ul = $(abcd).parent().parent();

    if (index != 2) {//选择题必须保留2个以上选项
        if (ul.children("li.editorItem").length > 2) {
            //删除答案选项
            var currentIndex = ul.children("li.editorItem").index($(abcd).parent("li.editorItem"));
            var answers = ul.siblings(".right-xuanxiang").children(".xuanxiang-group");
            answers.children().eq(currentIndex).remove();

            //删除答案后重新排序
            for (var i = 0; i < answers.children().length; i++) {
                answers.children().eq(i).html(String.fromCharCode(65 + i));
            }

            var thisParent = $(abcd).parent();
            var editorDiv = thisParent.children(".editorDiv");
            if (editorDiv.length) {
                var edui = editorDiv.children(".edui-container");
                if (edui.length) {
                    $('#tiganInfo').parents('.tigan-text').append(editorDiv);
                }
            }

            thisParent.remove();
            optionsReorder(ul.children("li.item"));
        }
        else {
            layer.msg("最少需要两个选项！");
        }
    }
    else {//填空题至少保留一空        
        if (ul.children("li.editorItem").length > 1) {
            $(abcd).parent().remove();
            //计算分数
            var items = $("#tab3>ul>li.item");
            var count = items.length;
            for (var i = 0; i < items.length; i++) {
                items.eq(i).children("span").text("空" + (i + 1));
            }
            $("#allBlankScore").html(parseInt(score.val()) * count);
            if (ul.children("li.editorItem").length == 1) {
                ul.children("li.other-function4").hide();
            }
        }
        else {
            layer.msg('最少需要一个答案！');
        }
    }
}


//选择题从新排序 pointer为选项jquery节点
function optionsReorder(pointer) {
    var sItem = pointer.children("span.item");
    var len = sItem.length;

    for (var i = 0; i < len; i++) {
        sItem.eq(i).html(String.fromCharCode(65 + i));
    }
}

//获取文章标题
function getUrl() {
    var queryString = unescape(location.search);
    var theRequest = new Object();
    if (queryString.indexOf("?") != -1) {
        var str = queryString.substr(1);
        strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
        }
    }
    return theRequest;
}

//转化题目类型为中文名
function TypeValueToChineseName(typeValue) {
    if (typeValue > 0 && typeValue < 6) {
        switch (typeValue) {
            case 1: questionInfo.typeValueChineseName = "单选"; break;
            case 2: questionInfo.typeValueChineseName = "多选"; break;
            case 3: questionInfo.typeValueChineseName = "填空"; break;
            case 4: questionInfo.typeValueChineseName = "判断"; break;
            case 5: questionInfo.typeValueChineseName = "简答"; break;
        }
    }
}

//转化题目中文名为类型
function ChineseNameToTypeValue(chineseName) {
    switch ($.trim(chineseName)) {
        case "单选": questionInfo.typeValue = 1; break;
        case "多选": questionInfo.typeValue = 2; break;
        case "填空": questionInfo.typeValue = 3; break;
        case "判断": questionInfo.typeValue = 4; break;
        case "简答": questionInfo.typeValue = 5; break;
    }
}

//页面试题重新排序
function questionsReorder() {
    var gq = $(".group-question");
    if (gq.length > 0) {
        for (var i = 0; i < gq.length; i++) {
            gq.eq(i).children().children(".tigan").children(".tihao").html(i + 1);
        }
    }
}

//刷新章节序号
function updateSectionOrder() {
    var qt = $(".question-title");
    if (qt.length > 0) {
        for (var i = 0; i < qt.length; i++) {
            qt.eq(i).children().children(".sectionOrder").html(Arabia_To_SimplifiedChinese(i + 1));
        }
    }
}

//加载左侧标题
function initialLeftCatalogue() {
    var container = $(".paper-all");
    container.children().remove();
    var wrap = '<div class="sectionWrap">' +
                 '<div class="paper-title paper-title-up">' +
                     '<a href="javascript:void(0)" class="sub-nav-title"></a>' +
                 '</div>' +
                 '<ul class="child-list"></ul>' +
            '</div>';
    var li = '<li class="child"><a href="javascript:void(0)"></a></li>';

    var sectionTitle = $(".question-review .question-title");
    if (sectionTitle.length > 0) {
        for (var i = 0; i < sectionTitle.length; i++) {
            container.append(wrap);
            var originalSideTitleStr = $.trim(sectionTitle.eq(i).children().children(".sectionTitle").text());
            var sideTitleStr = sectionTitle.eq(i).children().children(".sectionOrder").text() + "." + cutString(originalSideTitleStr, 23 - sectionTitle.eq(i).children().children(".sectionOrder").text().length);

            $(".sub-nav-title").eq(i).html(htmlEncodeJQ(sideTitleStr));
            $(".child-list").eq(i).attr("data-sectionguid", sectionTitle.eq(i).attr("data-sectionguid"));
            if (sectionTitle.eq(i).attr("data-questiontype")) {
                $(".child-list").eq(i).attr("data-questiontype", sectionTitle.eq(i).attr("data-questiontype"));
            }

            var question = sectionTitle.eq(i).siblings(".group-question");
            for (var j = 0; j < question.length; j++) {
                $(".child-list").eq(i).append(li);

                var sideSubTitleStr;
                var originalSideSubTitleStr = $.trim(question.eq(j).children().children(".tigan").children(".name").text());
                //设置questionguid和试题名称
                if ($.trim(question.eq(j).children().children(".tigan").children(".name").text()).length > 0) {
                    sideSubTitleStr = question.eq(j).children().children(".tigan").children(".tihao").text() + "." + cutString(originalSideSubTitleStr, 28 - question.eq(j).children().children(".tigan").children(".tihao").text().length);
                }
                else {
                    sideSubTitleStr = question.eq(j).children().children(".tigan").children(".tihao").text() + "." + "图片";
                }
                $(".child-list").eq(i).children().eq(j).attr("data-questionguid", question.eq(j).attr("data-questionguid")).children("a").html(htmlEncodeJQ(sideSubTitleStr)).attr("title", originalSideSubTitleStr);

            }
            sideSubTitleStr = null;
        }
    }

    //添加左侧目录data-sequence
    for (var n = 0; n < $(".group-question").length; n++) {
        $(".child-list").children().eq(n).attr("data-sequence", n + 1);
    }

    //添加目录展开收起事件
    catalogToggle();

    // 调整章节样式
    checkSection();
}


//刷新左侧标题
function updateLeftCatalogue() {
    var container = $(".paper-all");
    container.children().remove();
    var wrap = '<div class="sectionWrap">' +
                 '<div class="paper-title paper-title-up">' +
                     '<a href="javascript:void(0)" class="sub-nav-title"></a>' +
                 '</div>' +
                 '<ul class="child-list"></ul>' +
            '</div>';
    var li = '<li class="child"><a href="javascript:void(0)"></a></li>';

    var sectionTitle = $(".question-review .question-title");
    if (sectionTitle.length > 0) {
        for (var i = 0; i < sectionTitle.length; i++) {
            container.append(wrap);

            var sideTitleStr = sectionTitle.eq(i).children().children(".sectionOrder").text() + "." + cutString(sectionTitle.eq(i).children().children(".sectionTitle").text(), 23 - sectionTitle.eq(i).children().children(".sectionOrder").text().length);
            $(".sub-nav-title").eq(i).html(htmlEncodeJQ(sideTitleStr));
            $(".child-list").eq(i).attr("data-sectionguid", sectionTitle.eq(i).attr("data-sectionguid"));
            if (sectionTitle.eq(i).attr("data-questiontype")) {
                $(".child-list").eq(i).attr("data-questiontype", sectionTitle.eq(i).attr("data-questiontype"));
            }

            var question = sectionTitle.eq(i).siblings(".group-question");
            for (var j = 0; j < question.length; j++) {
                $(".child-list").eq(i).append(li);
                var sideSubTitleStr;
                //设置questionguid和试题名称
                if ($.trim(question.eq(j).children().children(".tigan").children(".name").text()).length > 0) {
                    sideSubTitleStr = question.eq(j).children().children(".tigan").children(".tihao").text() + "." + cutString(question.eq(j).children().children(".tigan").children(".name").text(), 28 - question.eq(j).children().children(".tigan").children(".tihao").text().length);
                }
                else {
                    sideSubTitleStr = question.eq(j).children().children(".tigan").children(".tihao").text() + "." + "图片";
                }
                $(".child-list").eq(i).children().eq(j).attr("data-questionguid", question.eq(j).attr("data-questionguid")).children("a").html(htmlEncodeJQ(sideSubTitleStr));
            }
            sideSubTitleStr = null;
        }
    }

    //添加左侧目录data-sequence
    for (var n = 0; n < $(".group-question").length; n++) {
        $(".child-list").children().eq(n).attr("data-sequence", n + 1);
    }

    //添加目录展开收起事件
    catalogToggle();
}

//左侧目录展开收起
function catalogToggle() {
    var title = $(".sectionWrap .paper-title");
    var items = $(".sectionWrap .child-list");
    var time = 200;
    var flag = false;
    var $this = null;

    title.unbind("click").click(function () {
        var cl = $(this).siblings(".child-list");
        if (cl.css("display") == "block") {
            //cl.css("display", "none");
            cl.slideUp(time);
            $(this).removeClass("paper-title-up");
        }
        else {
            //cl.css("display", "block");
            cl.slideDown(time);
            $(this).addClass("paper-title-up");
        }
    })
}

//鼠标移动到章节标题栏上，编辑/删除显隐
function displayTitleTool() {
    //var sectionTitleBlock = $(".small-icon-left");
    //sectionTitleBlock.css("display", "none");//章节标题编辑/删除 初始状态隐藏
    //$(".question-block .question-title").hover(function () {
    //    $(this).children(".small-icon-left").show();
    //}, function () {
    //    $(this).children(".small-icon-left").hide();
    //})
}

//编辑章节标题，p为章节中的.edit,mark为真表示新创建章节标题，mark为false表示为修改章节标题
function editTitle(p, mark, flag) {
    //获取标题在试卷中的次序
    var titleWrap = $(".question-title");
    var index = titleWrap.index(p.parent().parent()); //获取所点击的标题的次序号
    var columnName = p.parent().siblings(".question-title-content").children(".sectionTitle").text();

    if (examPaperForm == 1 || !mark) {
        //页面层
        var layerControl = layer.open({
            type: 1,
            title: ["栏目新名称", "background-color: #ffc600; font-size: 18px; line-height: 42px; padding-left: 20px;"],
            skin: '', //加上边框 layui-layer-rim
            area: ['578px', 'auto'], //宽高
            content: '<div id="modifyTitle">' +
                        '<div class="open-content">' +
                            '<div class="col-content clearfix">' +
                                '<div class="col-title">' +
                                    '<div class="col-name">栏目：</div>' +
                                    '<div class="input-block">' +
                                        '<label for="col-name4"></label>' +
                                        '<input type="text" id="col-name4" class="col-name input_item" maxLength="20">' +
                                    '</div>' +
                                '</div>' +
                            '</div>' +
                        '</div>' +
                        '<div class="open-button">' +
                            '<div class="open-container clearfix"><a href="javascript:void(0)" class="cancel">取 消</a><a href="javascript:void(0)" class="save">保 存</a></div>' +
                        '</div>' +
                    '</div>',
            cancel: function () {
                if (mark) {
                    p.parent().parent().parent().remove();
                }
            }
        });
    }


    if (examPaperForm == 2 && mark) {
        //页面层
        var layerControl = layer.open({
            type: 1,
            title: ["栏目新名称", "background-color: #ffc600; font-size: 18px; line-height: 42px; padding-left: 20px;"],
            skin: '', //加上边框 layui-layer-rim
            area: ['578px', 'auto'], //宽高
            content: '<div id="modifyTitle">' +
                        '<div class="open-add-content2">' +
                              '<div class="open-content">' +
                                '<div class="col-content clearfix">' +
                                  '<div class="col-title">' +
                                    '<div class="col-name">栏目：</div>' +
                                    '<div class="label-name" id="new-col-label" data-questionType=1>单选题</div>' +
                                    '<div class="input-block">' +
                                      '<label for="col-name3"></label>' +
                                      '<input type="text" class="col-name input_item" id="col-name3" maxLength="20">' +
                                    '</div>' +
                                  '</div>' +
                                '</div>' +
                                '<div class="question-type">题型选择 <span class="tooltip">题型确认后将不可更改</span></div>' +
                                '<div class="input-radio clearfix">' +
                                  '<div class="input-block new-col-label" data-questionType=1>' +
                                    '<div class="input-radio-block">' +
                                      '<input type="radio" checked="" id="danxuan" name="tixing">' +
                                    '</div>' +
                                    '<label for="danxuan">单选题</label>' +
                                  '</div>' +
                                  '<div class="input-block new-col-label" data-questionType=2>' +
                                    '<div class="input-radio-block">' +
                                      '<input type="radio" id="duoxuan" name="tixing">' +
                                    '</div>' +
                                    '<label for="duoxuan">多选题</label>' +
                                  '</div>' +
                                  '<div class="input-block new-col-label" data-questionType=3>' +
                                    '<div class="input-radio-block">' +
                                      '<input type="radio" id="tiankong" name="tixing">' +
                                    '</div>' +
                                    '<label for="tiankong">填空题</label>' +
                                  '</div>' +
                                '</div>' +
                                '<div class="input-radio clearfix">' +
                                  '<div class="input-block new-col-label" data-questionType=4>' +
                                    '<div class="input-radio-block">' +
                                      '<input type="radio" id="panduan" name="tixing">' +
                                    '</div>' +
                                    '<label for="panduan">判断题</label>' +
                                  '</div>' +
                                  '<div class="input-block new-col-label" data-questionType=5>' +
                                    '<div class="input-radio-block">' +
                                      '<input type="radio" id="jiandax" name="tixing">' +
                                    '</div>' +
                                    '<label for="jiandax">简答题</label>' +
                                  '</div>' +
                                '</div>' +
                              '</div>' +
                              '<div class="open-button">' +
                                '<div class="open-container clearfix"><a class="cancel" href="javascript:void(0)">取 消</a><a class="save" href="javascript:void(0)">添 加</a></div>' +
                              '</div>' +
                            '</div>' +
                     '</div>',
            cancel: function () {
                if (mark) {
                    $(".question-review").last().prev().append($("#editArea")); //删除前移除编辑区域
                    p.parent().parent().parent().remove();
                }
            }
        });
    }




    input = $("#modifyTitle input");
    if (examPaperForm == 2 && mark) {
        input = $("#col-name3");
        var randomRadio = $("#modifyTitle .open-content .input-radio .input-block");
        var randomTx = $("#new-col-label");
        //选择题型
        randomRadio.click(function () {
            randomTx.html($(this).text()).attr("data-questionType", $(this).attr("data-questionType"));
        })
    }
    save = $("#modifyTitle .save");
    cancel = $("#modifyTitle .cancel");
    input.focus().val(columnName).select();

    //保存标题
    save.unbind("click").click(function () {

        var titleName = $.trim(input.val());

        //验证是否含有特殊字符
        if (checkInput(titleName)) {
            titleWrap.eq(index).children().children(".sectionOrder").html(Arabia_To_SimplifiedChinese(index + 1));
            //修改章节标题
            if (titleName !== "") {

                titleWrap.eq(index).children().children(".sectionTitle").html(titleName);
                var qType = "";
                if (examPaperForm == 2 && mark) {
                    qType = $("#new-col-label").attr("data-questionType");
                    titleWrap.eq(index).attr("data-questionType", qType);
                    titleWrap.eq(index).children().children(".randomTx").html("(" + $("#new-col-label").html() + ")");
                }

                var loadingLayer = loadingAnimation();


                //添加新栏目
                if (mark) {
                    //ajax
                    $.post(DomainUrlHelper.InstituCenterAction + "api/apipaper/createsection", {
                        sectionName: titleName,
                        examPaperGUID: getPaperGuid(),
                        questionType: qType,
                        sequenceNum: index + 1
                    }, function (data) {
                        consoleLog(data);
                        if (data.ErrorCode == "E0006") {
                            questionInfo.sectionGUID = data.SectionGuid;
                            titleWrap.eq(index).attr("data-sectionGuid", data.SectionGuid); //设置guid存到页面上
                            layer.close(layerControl);

                            //刷新左侧标题
                            updateLeftCatalogue();
                            //初始化试题目录
                            initSortalbe();
                            // 调整章节样式
                            checkSection();

                            //判断是直接添加目录还是通过试卷目录管理添加目录
                            if (flag) {
                                layer.closeAll('page');
                                //试卷目录管理
                                catalogueManage();
                            }
                        }
                        layer.close(loadingLayer);
                    })
                }
                    //修改栏目
                else {
                    //非默认栏目
                    if (titleWrap.eq(index).attr("data-sectionguid").length) {
                        //ajax
                        $.post(DomainUrlHelper.InstituCenterAction + "api/apipaper/editsection", {
                            sectionName: titleName,
                            examPaperGUID: getPaperGuid(),
                            sectionGuid: titleWrap.eq(index).attr("data-sectionguid"),
                            sequenceNum: index + 1
                        }, function (data) {
                            consoleLog(data);
                            if (data.ErrorCode == "E0006") {
                                questionInfo.sectionGUID = data.SectionGuid;
                                layer.close(layerControl);

                                //刷新左侧标题
                                updateLeftCatalogue();
                                //初始化试题目录
                                initSortalbe();
                                // 调整章节样式
                                checkSection();
                            }
                            layer.close(loadingLayer);
                        })
                    }
                    else {
                        //默认栏目
                        //ajax
                        $.post(DomainUrlHelper.InstituCenterAction + "api/apipaper/createsection", {
                            sectionName: titleName,
                            examPaperGUID: getPaperGuid()
                        }, function (data) {
                            consoleLog(data);
                            if (data.ErrorCode == "E0006") {
                                questionInfo.sectionGUID = data.SectionGuid;
                                titleWrap.eq(index).attr("data-sectionGuid", data.SectionGuid); //设置guid存到页面上
                                layer.close(layerControl);

                                //刷新左侧标题
                                updateLeftCatalogue();
                                //初始化试题目录
                                initSortalbe();
                                // 调整章节样式
                                checkSection();

                            }
                            layer.close(loadingLayer);
                        })
                    }
                }
            }
            else {//章节标题为空
                layer.msg("栏目标题不能为空！");
                return;
            }

            ////判断是直接添加目录还是通过试卷目录管理添加目录
            //if (flag) {
            //    layer.closeAll('page');
            //    //试卷目录管理
            //    catalogueManage();
            //}

            //初始化左侧目录拖动排序功能
            initSortalbe();
            // 调整章节样式
            checkSection();
        }
        else {
            layer.msg("栏目名称不能包含特殊字符！")
        }


    })

    //取消修改标题
    cancel.unbind("click").click(function () {
        //$(this).parent().parent().parent().css("display", "none");
        layer.close(layerControl);
        if (mark) {
            $(".question-review").last().prev().append($("#editArea")); //删除前移除编辑区域
            p.parent().parent().parent().remove();
        }
    })
    //popClose.click(function () {
    //    $(this).parent().parent().css("display", "none");
    //})
};

//获取不同题型信息
function getQuestionInfo(index) {

    var items = options.eq(index).children("ul").children(".item");//选项集合
    questionInfo.itemsTotal = items.length; //选项数目

    questionInfo.typeValue = index + 1;//题型类别
    questionInfo.typeValueChineseName = TypeValueToChineseName(index + 1); //转化为中文名

    questionInfo.options = []; //清空选项值
    questionInfo.standarAnswer = []; //清空正确答案
    questionInfo.optionObj.Key = "";
    questionInfo.optionObj.Value = "";

    //当题目为单选1或者多选2或者判断4时，将答案存入数组
    var tv = parseInt(questionInfo.typeValue);

    //单选和多选 获取标准答案
    if (tv == 1 || tv == 2) {
        var answer = options.eq(index).find(".xuanxiang-group a");
        for (var i = 0; i < questionInfo.itemsTotal; i++) {
            (function (j) {
                var tempObj = new Object();
                tempObj.Key = String.fromCharCode(65 + i);
                tempObj.Value = unescape(items.eq(i).children(".editorDiv").children(".optionInput").html());
                questionInfo.options.push(tempObj);
            })(i)

            if (answer.eq(i).hasClass("selected")) {
                questionInfo.standarAnswer += String.fromCharCode(i + 65); //将正确答案的序号存入数组
            }

        }
    }


    //填空题 多个填空题答案使用#$$#分隔
    if (tv == 3) {
        var tAnswer = options.eq(index).find("input.tiankong_inputContent");
        if (tAnswer.length != 1) {
            for (var j = 0; j < tAnswer.length; j++) {
                if (j != tAnswer.length - 1) {
                    questionInfo.standarAnswer += $.trim(tAnswer.eq(j).val()) + "#$$#";
                }
                else {
                    questionInfo.standarAnswer += $.trim(tAnswer.eq(j).val());
                }
            }
        }
        else {
            questionInfo.standarAnswer = $.trim(tAnswer.val());
        }
        if ($("#UnCheckAnsSeqInput").is(":checked")) {
            questionInfo.standarAnswer += "%*%";
        }
    }

    //判断题
    if (tv == 4) {
        var answer = options.eq(index).find(".xuanxiang-group a");
        for (var i = 0; i < 2; i++) {
            if (answer.eq(i).hasClass("selected")) {
                questionInfo.standarAnswer += String.fromCharCode(i + 65); //将正确答案的序号存入数组
            }
        }
    }

    //简答题
    if (tv == 5) {
        questionInfo.standarAnswer = options.eq(index).find("#jianda").html();//htmlEncodeJQ(options.eq(index).find("#jianda").html());
    }
}

//设置编辑区域的内容
function setValueToEditArea(obj) {

    $(".zhishidian-block").children("label").hide();
    $("#tiganInfo").html(questionInfo.tigan);
    if ($.trim(questionInfo.AnswerAnalysis)) {
        $("#explanation").show();
        $("#explanation-tab").hide();
        $("#explanation .optionInput").html(questionInfo.AnswerAnalysis);
    }


    //知识点
    var knowledgeHtml = "";
    var knowledgePointStr = "";
    for (var j = 0; j < questionInfo.knowledgePoint.length; j++) {
        knowledgeHtml += '<li class="tagit-choice ui-widget-content ui-state-default ui-corner-all tagit-choice-editable">' +
                            '<span class="tagit-label">' + questionInfo.knowledgePoint[j] + '</span>' +
                            '<a class="tagit-close">' +
                                '<span class="text-icon">×</span>' +
                                '<span class="ui-icon ui-icon-close"></span>' +
                            '</a>' +
                        '</li>';
        knowledgePointStr = knowledgePointStr + questionInfo.knowledgePoint[j] + ',';
    }
    $(knowledgeHtml).insertBefore("#singleFieldTags .tagit-new");
    $("#zhishidian").val(knowledgePointStr.substring(0, knowledgePointStr.length - 1));

    //添加知识点绑定事件
    $(".tagit-close").click(function () {
        $(this).parent().remove();
        var knowledgePointStrNew = "";
        $('#singleFieldTags span.tagit-label').each(function () {
            knowledgePointStrNew = knowledgePointStrNew + $(this).html() + ',';
        });
        $("#zhishidian").val(knowledgePointStrNew.substring(0, knowledgePointStrNew.length - 1));
    })

    //设置试题类型
    var tx = $("#tixing");
    var aList = tx.children("ul").children("li").children("a");
    aList.removeClass("selected").eq(questionInfo.typeValue - 1).addClass("selected");
    if (examPaperForm == 2) {
        aList.hide().eq(questionInfo.typeValue - 1).show();
    }

    tx.siblings(".option").hide().eq(questionInfo.typeValue - 1).show();

    var htmlStr = "";

    //设置选项内容
    if (questionInfo.typeValue == 1 || questionInfo.typeValue == 2) {
        tx.siblings(".option").eq(questionInfo.typeValue - 1).children("ul,.right-xuanxiang").remove();

        //选择题
        var lis = "";
        var answerString = "";
        var isSelected = "";
        for (var i = 0; i < questionInfo.options.length; i++) {

            lis += '<li class="clearfix item editorItem">' +
                      '<span class="item">' + questionInfo.options[i].Key + '</span>' +
                      '<div class="editorDiv"><div class="optionInput">' + questionInfo.options[i].Value + '</div></div>' +
                      '<a class="false" onclick="DeleteOption(this)" href="javascript:void(0)"></a>' +
                   '</li>';

            //显示已选答案
            if (questionInfo.standarAnswer) {
                if (questionInfo.standarAnswer.indexOf(String.fromCharCode(i + 65)) != -1) {
                    isSelected = "selected";
                }
            }

            answerString += '<a href="javascript:void(0)" class="' + isSelected + '">' + String.fromCharCode(i + 65) + '</a>'
            isSelected = "";
        }
        var lif = '<li class="other-function">' +
            '<a class="danxuan-addtxt" href="javascript:void(0)">+添加选项</a>' +
            '</li>';

        lis = lis + lif;
        htmlStr = '<ul>' + lis + '</ul>' +
                  '<div class="right-xuanxiang clearfix">' +
                  '<label>答案:</label>' +
                  '<div class="xuanxiang-group clearfix">' + answerString + '</div>' +
                  '</div>';
    }

    //判断题
    if (questionInfo.typeValue == 4) {
        var tab4A = $("#tab4 .xuanxiang-group a");
        tab4A.removeClass("selected");
        if (questionInfo.standarAnswer == "A") {
            tab4A.eq(0).addClass("selected");
        }
        else {
            tab4A.eq(1).addClass("selected");
        }
    }

    //填空题
    if (questionInfo.typeValue == 3) {
        $("#allBlankScore").parent().show();
        //$("#tab3 ul li .editorDiv .optionInput").show();
        $("#tab3>ul>li").show();

        if (questionInfo.standarAnswer.indexOf("%*%") >-1) {
            questionInfo.standarAnswer=questionInfo.standarAnswer.replace("%*%", "");
            $("#UnCheckAnsSeqInput").attr("checked", true);
        }
        var tArray = questionInfo.standarAnswer.split("#$$#");

        //tx.siblings(".option").eq(questionInfo.typeValue - 1).children("ul").remove();
        //选择题和判断题
        var ul = $("#tab3>ul");
        var firstli = ul.children("li.item").first();
        for (var i = 0; i < tArray.length; i++) {
            var li0 = firstli.clone(false);
            li0.children("input").val(tArray[i]);
            li0.find("ul").html("").removeClass().addClass("tiankong_ul");
            li0.children("span").text("空" + (i + 1));
            li0.insertBefore(ul.find(".other-function4"));
            AddTagitEvent(li0,false);
        }
        firstli.remove();
    }

    //简答题
    if (questionInfo.typeValue == 5) {
        //设置简答题答案
        $("#jianda").html(questionInfo.standarAnswer);
        //tx.siblings(".option").eq(questionInfo.typeValue - 1).children("ul").children("li").children("input").val(questionInfo.standarAnswer);

    }

    //设置分数
    //填空题
    if (questionInfo.typeValue == 3) {
        $("#allBlankScore").html(questionInfo.score);
        var count = tArray.length;
        score.val(parseInt(questionInfo.score) / count + "分");
    }
    else {
        score.val(questionInfo.score + "分");
    }

    tx.siblings(".option").eq(questionInfo.typeValue - 1).append(htmlStr);
}

//生成选择题字符串
function generateChoiceQ(obj, questionGuid) {
    var random = Math.random();
    var choiceQustionStr = "";
    var choiceQustionOptionStr = "";
    var choiceQustionknowledgePointStr = "";

    //选择题知识点字符串
    if ($.trim(questionInfo.knowledgePoint).length) {
        for (var j = 0; j < questionInfo.knowledgePoint.length; j++) {
            choiceQustionknowledgePointStr += '<li>' + questionInfo.knowledgePoint[j] + '</li>';
        }
    }

    //生成试题解析字符串
    var AnswerAnalysisStr = '';
    if (questionInfo.AnswerAnalysis != null && questionInfo.AnswerAnalysis != "") {
        AnswerAnalysisStr = '<div class="shitijiexi clearfix">' +
                                '<div class="intro">试题解析：</div>' +
                                '<div class="jiexi-content" id="jiexi">' +
                                    questionInfo.AnswerAnalysis +
                                '</div>' +
                            '</div>';
    }
    var blankZhishidianBottom = "";//知识点和试题解析div
    if (choiceQustionknowledgePointStr != "" || AnswerAnalysisStr != "") {
        blankZhishidianBottom = '<div class="zhishidian-bottom" style="margin-left: -66px; margin-right: 0; padding: 15px 0 15px 66px;">' +
                              (choiceQustionknowledgePointStr != "" ? '<div class="zhishidian-show clearfix"><div class="intro">知识点:</div><ul>' + choiceQustionknowledgePointStr + '</ul></div>' : '') +
                          AnswerAnalysisStr +
                        '</div>'
    }
    for (var i = 0; i < questionInfo.itemsTotal; i++) {

        //单选题
        if (questionInfo.typeValue == 1) {


            choiceQustionOptionStr += '<li class="clearfix">' +
                                         '<div class="radio">' +
                                            '<div class="input-block">' +
                                                '<input type="radio" name="radio' + random + '" disabled="disabled" >' +
                                                '<span class="xuanxiang">' + questionInfo.options[i].Key + '. </span>' +
                                            '</div>' +
                                            '<label for="">' + questionInfo.options[i].Value + '</label>' +
                                        '</div>' +
                                      '</li>';

        }

        //多选题
        if (questionInfo.typeValue == 2) {

            choiceQustionOptionStr += '<li class="clearfix">' +
                                            '<div class="radio">' +
                                                '<div class="input-block">' +
                                                    '<input type="checkbox" disabled="disabled" >' +
                                                    '<span class="xuanxiang">' + questionInfo.options[i].Key + '. </span>' +
                                                '</div>' +
                                                '<label for="">' + questionInfo.options[i].Value + '</label>' +
                                            '</div>' +
                                      '</li>';

        }

        if (examPaperForm == 1) {
            choiceQustionStr =
                            '<div class="group-question" data-questionguid=' + questionGuid + '>' +
                                '<div class="question-item-review">' +
                                    '<div class="tigan"><span class="tihao">' + questionInfo.order + '</span>.<span class="name">' + questionInfo.tigan + '</span>（<span class="type">' + questionInfo.typeValueChineseName + ' </span> <span class="red-value score">' + questionInfo.score + '分</span>）</div>' +
                                    '<ul class="question-list">' +
                                        choiceQustionOptionStr +
                                    '</ul>' +
                                    blankZhishidianBottom +
                                    '<div class="small-right-icon" style="display:none;">' +
                                        '<a class="edit" href="javascript:void(0)" title="编辑试题"></a>' +
                                        '<a class="delete" href="javascript:void(0)" title="删除试题"></a>' +
                                        '<a class="add" href="javascript:void(0)" title="添加新题"></a>' +
                                    '</div>' +
                                '</div>' +
                            '</div>';
        }
        if (examPaperForm == 2) {
            choiceQustionStr =
                            '<div class="group-question" data-questionguid=' + questionGuid + '>' +
                                '<div class="question-item-review">' +
                                    '<div class="tigan"><span class="tihao">' + questionInfo.order + '</span>.<span class="name">' + questionInfo.tigan + '</span></div>' +
                                    '<ul class="question-list">' +
                                        choiceQustionOptionStr +
                                    '</ul>' +
                                    blankZhishidianBottom +
                                    '<div class="small-right-icon" style="display:none;">' +
                                        '<a class="edit" href="javascript:void(0)" title="编辑试题"></a>' +
                                        '<a class="delete" href="javascript:void(0)" title="删除试题"></a>' +
                                        '<a class="add" href="javascript:void(0)" title="添加新题"></a>' +
                                    '</div>' +
                                '</div>' +
                            '</div>';
        }

    }



    return choiceQustionStr;
}
//生成判断题字符串
function generateYesOrNoQ(obj, questionGuid) {
    var random = Math.random();
    var choiceQustionStr = "";
    var choiceQustionOptionStr = "";
    var choiceQustionknowledgePointStr = "";

    //判断题知识点字符串
    if ($.trim(questionInfo.knowledgePoint).length) {
        for (var j = 0; j < questionInfo.knowledgePoint.length; j++) {
            choiceQustionknowledgePointStr += '<li>' + questionInfo.knowledgePoint[j] + '</li>';
        }
    }

    //判断题选项字符串
    choiceQustionOptionStr += '<li class="clearfix">' +
                                   '<div class="input-block">' +
                                     '<input type="radio" name="danxuan' + random + '" id="right-radio" disabled="disabled" >' +
                                  '</div>' +
                                  '<label for="right-radio">正确</label>' +
                                '</li>' +
                                '<li class="clearfix">' +
                                   '<div class="input-block">' +
                                     '<input type="radio" name="danxuan' + random + '" id="wrong-radio" disabled="disabled" >' +
                                  '</div>' +
                                  '<label for="wrong-radio">错误</label>' +
                                '</li>';

    //生成试题解析字符串
    var AnswerAnalysisStr = '';
    if (questionInfo.AnswerAnalysis != null && questionInfo.AnswerAnalysis != "") {
        AnswerAnalysisStr = '<div class="shitijiexi clearfix">' +
                                '<div class="intro">试题解析：</div>' +
                                '<div class="jiexi-content" id="jiexi">' +
                                    questionInfo.AnswerAnalysis +
                                '</div>' +
                            '</div>';
    }

    var choiceQustionStr = "";//判断题字符串
    var blankZhishidianBottom = "";//知识点和试题解析div
    if (choiceQustionknowledgePointStr != "" || AnswerAnalysisStr != "") {
        blankZhishidianBottom = '<div class="zhishidian-bottom" style="margin-left: -66px; margin-right: 0; padding: 15px 0 15px 66px;">' +
                              (choiceQustionknowledgePointStr != "" ? '<div class="zhishidian-show clearfix"><div class="intro">知识点:</div><ul>' + choiceQustionknowledgePointStr + '</ul></div>' : '') +
                          AnswerAnalysisStr +
                        '</div>'
    }
    if (examPaperForm == 1) {
        choiceQustionStr =
                        '<div class="group-question" data-questionguid=' + questionGuid + '>' +
                            '<div class="question-item-review">' +
                                '<div class="tigan"><span class="tihao">' + questionInfo.order + '</span>.<span class="name">' + questionInfo.tigan + '</span>（<span class="type">' + questionInfo.typeValueChineseName + ' </span> <span class="red-value score">' + questionInfo.score + '分</span>）</div>' +
                                '<ul class="question-list">' +
                                    choiceQustionOptionStr +
                                '</ul>' +
                                blankZhishidianBottom +
                                '<div class="small-right-icon" style="display:none;">' +
                                    '<a class="edit" href="javascript:void(0)" title="编辑试题"></a>' +
                                    '<a class="delete" href="javascript:void(0)" title="删除试题"></a>' +
                                    '<a class="add" href="javascript:void(0)" title="添加新题"></a>' +
                                '</div>' +
                            '</div>' +
                        '</div>';
    }
    if (examPaperForm == 2) {
        choiceQustionStr =
                        '<div class="group-question" data-questionguid=' + questionGuid + '>' +
                            '<div class="question-item-review">' +
                                '<div class="tigan"><span class="tihao">' + questionInfo.order + '</span>.<span class="name">' + questionInfo.tigan + '</span></div>' +
                                '<ul class="question-list">' +
                                    choiceQustionOptionStr +
                                '</ul>' +
                                blankZhishidianBottom +
                                '<div class="small-right-icon" style="display:none;">' +
                                    '<a class="edit" href="javascript:void(0)" title="编辑试题"></a>' +
                                    '<a class="delete" href="javascript:void(0)" title="删除试题"></a>' +
                                    '<a class="add" href="javascript:void(0)" title="添加新题"></a>' +
                                '</div>' +
                            '</div>' +
                        '</div>';
    }

    return choiceQustionStr;
}
//生成填空题字符串
function generateBlankQ(obj, questionGuid) {
    var blankQustionStr = "";
    var blankQustionknowledgePointStr = "";

    //选择题知识点字符串
    if ($.trim(questionInfo.knowledgePoint).length) {
        for (var j = 0; j < questionInfo.knowledgePoint.length; j++) {
            blankQustionknowledgePointStr += '<li>' + questionInfo.knowledgePoint[j] + '</li>';
        }
    }

    //生成答案数组
    var tkString = "";
    var unCheckAnsSeqStr = "";
    if (questionInfo.standarAnswer.indexOf("%*%") > -1) {
        unCheckAnsSeqStr = '<div class="jiaoyan-info">评分时不校验填空顺序</div>';
        questionInfo.standarAnswer=questionInfo.standarAnswer.replace("%*%", "");
    }

    var answers = questionInfo.standarAnswer.split("#$$#");
    for (var al = 0; al < answers.length; al++) {
        var thisAnswer = answers[al];

        thisAnswer = thisAnswer.replace(new RegExp("&@&", "g"), '<span class="color-grey"> 或 </span>');
        tkString += '<li class="clearfix">' +
                        '<label class="red-value-tiankong">' + thisAnswer + '</label>' +
                    '</li>';
    }
  
    //生成试题解析字符串
    var AnswerAnalysisStr = '';
    if (questionInfo.AnswerAnalysis != null && questionInfo.AnswerAnalysis != "") {
        AnswerAnalysisStr = '<div class="shitijiexi clearfix">' +
                                '<div class="intro">试题解析：</div>' +
                                '<div class="jiexi-content" id="jiexi">' +
                                    questionInfo.AnswerAnalysis +
                                '</div>' +
                            '</div>';
    }

    var blankQustionStr = "";//填空题字符串
    var blankZhishidianBottom = "";//知识点和试题解析div
    if (blankQustionknowledgePointStr != "" || AnswerAnalysisStr != "") {
        blankZhishidianBottom = '<div class="zhishidian-bottom" style="margin-left: -66px; margin-right: 0; padding: 15px 0 15px 66px;">' +
                              (blankQustionknowledgePointStr != "" ? '<div class="zhishidian-show clearfix"><div class="intro">知识点:</div><ul>' + blankQustionknowledgePointStr + '</ul></div>' : '') +
                          AnswerAnalysisStr +
                        '</div>'
    }
    if (examPaperForm == 1) {

        blankQustionStr =
                    '<div class="group-question" data-questionguid=' + questionGuid + '>' +
                        '<div class="question-item-review">' +
                            '<div class="tigan"><span class="tihao">' + questionInfo.order + '</span>.<span class="name">' + questionInfo.tigan + '</span>（<span class="type">' + questionInfo.typeValueChineseName + ' </span> <span class="red-value score">' + questionInfo.score + '分</span>）</div>' +
                            '<ul class="question-list">' + tkString + '</ul>' + unCheckAnsSeqStr +
                            blankZhishidianBottom +
                            '<div class="small-right-icon" style="display:none;">' +
                                '<a class="edit" href="javascript:void(0)" title="编辑试题"></a>' +
                                '<a class="delete" href="javascript:void(0)" title="删除试题"></a>' +
                                '<a class="add" href="javascript:void(0)" title="添加新题"></a>' +
                            '</div>' +
                        '</div>' +
                    '</div>';
    }
    if (examPaperForm == 2) {
        blankQustionStr =
                    '<div class="group-question" data-questionguid=' + questionGuid + '>' +
                        '<div class="question-item-review">' +
                            '<div class="tigan"><span class="tihao">' + questionInfo.order + '</span>.<span class="name">' + questionInfo.tigan + '</span></div>' +
                            '<ul class="question-list">' + tkString + '</ul>' + unCheckAnsSeqStr +
                            blankZhishidianBottom +
                            '<div class="small-right-icon" style="display:none;">' +
                                '<a class="edit" href="javascript:void(0)" title="编辑试题"></a>' +
                                '<a class="delete" href="javascript:void(0)" title="删除试题"></a>' +
                                '<a class="add" href="javascript:void(0)" title="添加新题"></a>' +
                            '</div>' +
                        '</div>' +
                    '</div>';
    }

    return blankQustionStr;
}
//设置试题答案
function setAnswer() {
    var currentQuestion = editArea.prev(".group-question");
    var answerStyle;
    //单选题
    if (questionInfo.typeValue == 1) {
        var correctNumber = questionInfo.standarAnswer.charCodeAt() - 65;
        answerStyle = currentQuestion.children().children("ul").children("li").eq(correctNumber);
        answerStyle.find("input").attr("checked", "checked");
        answerStyle.find("label").addClass("red-value");
    }

    //多选题
    if (questionInfo.typeValue == 2) {
        for (var i = 0; i < questionInfo.standarAnswer.length; i++) {
            currentQuestion.children().children("ul").children("li").eq(questionInfo.standarAnswer[i].charCodeAt() - 65).find("input").attr("checked", "checked");
            currentQuestion.children().children("ul").children("li").eq(questionInfo.standarAnswer[i].charCodeAt() - 65).find("label").addClass("red-value");
        }
    }

    //判断题
    if (questionInfo.typeValue == 4) {
        if (questionInfo.standarAnswer == "A") {
            answerStyle = currentQuestion.children().children("ul").children("li").eq(0);
            answerStyle.find("input").attr("checked", "checked");
            answerStyle.find("label").addClass("red-value");
        }
        if (questionInfo.standarAnswer == "B") {
            answerStyle = currentQuestion.children().children("ul").children("li").eq(1);
            answerStyle.find("input").attr("checked", "checked");
            answerStyle.find("label").addClass("red-value");
        }
    }
    answerStyle = null;
}

//生成试题同时添加绑定事件
function generateQuestion(obj, questionGuid) {


    var qr = $(".question-review");
    if (questionInfo.typeValue == 3 || questionInfo.typeValue == 5) {
        //将填空试题插入页面
        $(generateBlankQ(obj, questionGuid)).insertBefore(".editArea");
    }
    else if (questionInfo.typeValue == 4) {
        //将判断题插入页面
        $(generateYesOrNoQ(obj, questionGuid)).insertBefore(".editArea");
    }
    else {
        //将选择试题插入页面
        $(generateChoiceQ(obj, questionGuid)).insertBefore(".editArea");
    }

    //设置试题答案
    setAnswer();

    //添加dom节点事件
    //试题编辑栏编辑 修改等功能
    //试题编辑栏的显隐
    toggleEditAreaBar();

    //添加事件
    // 1、编辑试题
    editQuestion();

    // 2、删除试题
    deleteQuestion();

    // 3、当前试题后添加试题
    addQuestion();
}

//编辑试题
function editQuestion() {
    myEditor.hide();
    $("#tiganInfo").show();

    $(".question-review .small-right-icon a.edit").unbind("click").click(function () {
        var pointer = $(this);
        isEdit = true;//编辑试题的标识
        var groupQuestion = $(this).parent().parent().parent();
        var questionguid = groupQuestion.attr("data-questionguid");

        var loadingLayer = loadingAnimation();

        $.post(DomainUrlHelper.InstituCenterAction + "api/apipaper/getquestioninfo", {
            questionId: questionguid,
            paperId: getPaperGuid()
        }, function (data) {
            consoleLog(data);
            if (data.ErrorCode == "E0006") {

                //减去当前题目在栏目和浮动分数显示部分中的分数
                var currentQuestionScore = parseInt(groupQuestion.find(".score").html());
                var columnScore = groupQuestion.siblings(".question-title").find(".sectionScore");
                columnScore.html(columnScore.html() - currentQuestionScore);
                $("#currentScore").html($("#currentScore").html() - currentQuestionScore);

                //获取试题信息
                if (data.QuestionEntity.QuestionType == 5) {//简答题要包括一些标签
                    questionInfo.standarAnswer = data.QuestionEntity.StandardAnswer;
                }
                else {
                    questionInfo.standarAnswer = $("<div>").html(data.QuestionEntity.StandardAnswer).text();
                }

                questionInfo.sectionGUID = data.QuestionEntity.SectionGUID;
                questionInfo.tigan = data.QuestionEntity.Question;
                questionInfo.score = data.QuestionEntity.QuestionScore;
                if (data.QuestionEntity.KnowledgePoint != "" && data.QuestionEntity.KnowledgePoint) {
                    questionInfo.knowledgePoint = data.QuestionEntity.KnowledgePoint.split(";");
                }
                else {
                    questionInfo.knowledgePoint = "";
                }
                questionInfo.typeValue = data.QuestionEntity.QuestionType;
                index = data.QuestionEntity.QuestionType - 1;
                questionInfo.typeValueChineseName = TypeValueToChineseName(questionInfo.typeValue);
                questionInfo.options = eval(data.QuestionEntity.Option);
                questionInfo.order = parseInt(groupQuestion.children().children(".tigan").children(".tihao").html());
                questionInfo.questionGuid = data.QuestionEntity.QuestionGUID;
                questionInfo.AnswerAnalysis = data.QuestionEntity.AnswerAnalysis;

                //当sourceType为1表示新建试题，为2表示引用试题，引用试题不可编辑，只可修改分数
                if (data.QuestionEntity.SourceType == 1) {
                    //将获取的信息填充到编辑区域
                    editArea.css("display", "block").insertAfter(groupQuestion);
                    //moveEditAreaToTop();//移动编辑区域到顶部
                    resetEditArea();
                    setValueToEditArea(questionInfo);
                    optionAddAndDelete();//编辑区域-选择题选项添加与删除事件绑定
                    selectAnswer();//选择题与判断题答案选择
                    if (editorType == 'umeditor') {
                        toggleUMEditor();//编辑器与文本框切换-新版umeditor
                    } else if (editorType == 'ueditor') {
                        toggleEditor(); //编辑器与文本框切换-旧版ueditor
                    }
                    $(".group-question").show();
                    groupQuestion.hide();
                }

                if (data.QuestionEntity.SourceType == 2) { //引用试题
                    var tihao = pointer.parent().siblings(".tigan").children(".tihao").text();
                    var question_Score = data.QuestionEntity.QuestionScore;
                    if (data.QuestionEntity.QuestionType == 3) {
                        var answerCount = data.QuestionEntity.StandardAnswer.split("#$$#").length;
                        question_Score = question_Score / answerCount;
                    }
                    //分数设置弹出框
                    var setReferScores = layer.open({
                        type: 1,
                        title: ["设置分值", "background-color: #ffc600; font-size: 18px; line-height: 42px; padding-left: 20px;"],
                        skin: '', //加上边框 layui-layer-rim
                        area: ['488px', '230px'], //宽高
                        content: '<div class="m-setting-value">' +
                                    '<div class="g-body g-body2">' +
                                        '<div class="content">' +
                                            '<div class="item clearfix">' +
                                                '<div class="tigan tigan2">题号：' + tihao + ' &nbsp;设置分值：</div>' +
                                                '<div class="fenshu fenshu2">' +
                                                    '<div class="button-group clearfix"><a href="javascript:void(0)" class="button minus">-</a>' +
                                                        '<input id="setSingleScore" value="' + question_Score + '" maxlength="3" class="type-value score" type="text"><a href="javascript:void(0)" class="button plus">+</a>' +
                                                    '</div>' +
                                                '</div>' +
                                                '<div class="danwei">分/' + (data.QuestionEntity.QuestionType == 3 ? "空" : "题") + '</div>' +
                                            '</div>' +
                                        '</div>' +
                                    '</div>' +
                                    '<div class="g-foot">' +
                                        '<div class="g-foot-button clearfix"><a id="setSingleScoreCancel" href="javascript:void(0)" class="u-btn">取消</a><a id="setSingleScoreConfirm" href="javascript:void(0)" class="u-btn u-btn-confirm">确认</a></div>' +
                                    '</div>' +
                                  '</div>'
                    });

                    //绑定分数设置
                    setColloumQuestionScore($(".plus"), $(".minus"), $(".score"), true);


                    //单个试题设置分数-确认
                    $("#setSingleScoreConfirm").click(function () {
                        var loadingLayer = loadingAnimation();
                        var currentScore = $("#setSingleScore").val();
                        if (data.QuestionEntity.QuestionType == 3) {
                            var answerCount = data.QuestionEntity.StandardAnswer.split("#$$#").length;
                            currentScore = currentScore * answerCount;
                        }
                        if (currentScore != data.QuestionEntity.QuestionScore) {//分数有改动
                            $.post(DomainUrlHelper.InstituCenterAction + "api/apipaper/UpdateQuestionScore", {
                                questionGuid: questionguid,
                                examPaperGuid: getPaperGuid(),
                                score: currentScore
                            }, function (data) {
                                consoleLog(data);
                                if (data.ErrorCode == "E0006") {
                                    //修改当前试题的分值
                                    pointer.parent().siblings(".tigan").children(".score").html(currentScore);
                                    //设置栏目的总分
                                    setColumnScore();
                                    //计算当前所有栏目的总分值
                                    allSectionScore = getAllSectionScore();
                                    //设置浮动区域页面章节的总分
                                    $("#currentScore").html(allSectionScore);
                                }
                                layer.close(loadingLayer);
                                layer.close(setReferScores);
                            });
                        }
                        else {
                            //设置栏目的总分
                            setColumnScore();
                            //计算当前所有栏目的总分值
                            allSectionScore = getAllSectionScore();
                            //设置浮动区域页面章节的总分
                            $("#currentScore").html(allSectionScore);
                            layer.close(loadingLayer);
                            layer.close(setReferScores);
                        }
                    })

                    //单个试题设置分数-取消
                    $("#setSingleScoreCancel").click(function () {
                        //设置栏目的总分
                        setColumnScore();
                        //计算当前所有栏目的总分值
                        allSectionScore = getAllSectionScore();
                        //设置浮动区域页面章节的总分
                        $("#currentScore").html(allSectionScore);
                        layer.close(setReferScores);
                    })
                }
            }
            else {
                layer.msg(data.ErrorMessage);
            }
            layer.close(loadingLayer);
        })

    })
}



//删除试题
function deleteQuestion() {
    $(".question-review .small-right-icon a.delete").unbind("click").click(function () {
        var groupQuestion = $(this).parent().parent().parent();

        //询问框
        layer.confirm('确认删除试题？', {
            btn: ['删除', '取消'] //按钮
        },
        function (index) {
            layer.close(index);

            $.post(DomainUrlHelper.InstituCenterAction + "api/apipaper/RemoveQuestion", {
                questionGUID: groupQuestion.attr("data-questionguid"),
                paperGUID: getPaperGuid()
            }, function (data) {
                consoleLog(data);
                if (data.ErrorCode == "E0006") {
                    groupQuestion.remove();

                    //页面试题重新排序
                    questionsReorder();

                    //设置栏目的总分
                    setColumnScore();

                    //设置浮动区域页面章节的总分
                    $("#currentScore").html(getAllSectionScore());


                    //刷新左侧标题
                    updateLeftCatalogue();

                    //初始化左侧目录拖动排序功能
                    initSortalbe();
                    // 调整章节样式
                    checkSection();

                }
                else {
                    layer.msg("删除试题失败！")
                }



            })

        },
        function () { });
    })

}

//添加新题
function addQuestion() {
    $(".question-review .small-right-icon a.add").unbind("click").click(function () {
        //最多为1000道试题
        var groupQuestion = $(this).parent().parent().parent();
        editArea.insertAfter(groupQuestion);
        $(".group-question").show();
        isEdit = false;
        moveEditAreaToTop();//移动编辑区域到顶部
        resetEditArea();
        //editArea.show();

        //如果是随机试题
        if (examPaperForm == 2) {
            setEditAreaForRandom(groupQuestion.siblings(".question-title"));//隐藏随机试题非当前题型
        }

    })
}

//在栏目上点击添加新题
function addQuestionOnColumn() {
    $(".question-review .add-new-queston a.add").unbind("click").click(function () {
        var columnTitle = $(this).parent().parent();
        columnTitle.parent().append(editArea);

        $(".group-question").show();
        isEdit = false;
        resetEditArea();
        moveEditAreaToTop();//移动编辑区域到顶部
        //editArea.show();
        //如果是随机试题
        if (examPaperForm == 2) {
            setEditAreaForRandom(columnTitle);//隐藏随机试题非当前题型
        }
    })

}

//随机试题编辑区域设置 根据题型显示当前题型，其他隐藏 title是当前栏目
function setEditAreaForRandom(title) {
    var qType = title.attr("data-questiontype");
    index = qType - 1;
    //题目类型切换
    questionType.removeClass("selected").hide();
    questionType.eq(qType - 1).addClass("selected").show();
    options.hide();
    options.eq(qType - 1).show();
}

//生成栏目
function generateColumn() {


    var columnStr;

    if (examPaperForm == 1) {
        columnStr = '<div class="question-review">' +
                    '<div class="question-title clearfix" data-sectionguid="">' +
                        '<div class="question-title-content">' +
                            '<span class="sectionOrder">一</span>.<span class="core-title sectionTitle">栏目标题</span>（<span class="sectionScore">0</span>分）' +
                        '</div>' +
                        '<div class="small-icon-left clearfix">' +
                            '<a class="edit" href="javascript:void(0)" title="编辑栏目"></a>' +
                            '<a class="delete" href="javascript:void(0)" title="删除栏目"></a>' +
                        '</div>' +
                        '<div class="add-new-queston">' +
                            '<a class="add" href="javascript:void(0)">+ 添加新题</a>' +
                        '</div>' +
                    '</div>' +
                    '</div>';
    }
    if (examPaperForm == 2) {
        columnStr = '<div class="question-review">' +
                    '<div class="question-title clearfix" data-sectionguid="">' +
                        '<div class="question-title-content">' +
                            '<span class="sectionOrder">一</span>.<span class="core-title sectionTitle">栏目标题</span><span class="randomTx">(单选题)</span>' +
                        '</div>' +
                        '<div class="small-icon-left clearfix">' +
                            '<a class="edit" href="javascript:void(0)" title="编辑栏目"></a>' +
                            '<a class="delete" href="javascript:void(0)" title="删除栏目"></a>' +
                        '</div>' +
                        '<div class="add-new-queston">' +
                            '<a class="add" href="javascript:void(0)">+ 添加新题</a>' +
                        '</div>' +
                    '</div>' +
                    '</div>';
    }

    $(".section-question").append(columnStr); //插入栏目
    var qr = $(".question-review");
    qr.eq(qr.length - 1).append(editArea);

    //添加绑定事件

}

//重置选择题选项为默认状态
function resetOptionItems(t) {
    //重置答案选项标记,将答案标记为默认的第一个
    var tagA = t.siblings(".right-xuanxiang").children(".xuanxiang-group").children("a");
    tagA.removeClass("selected");

    var optionsLength = t.children("li.editorItem").length;
    if (optionsLength < 4) {

        for (var i = optionsLength; i < 4; i++) {

            var li = t.children("li.item").last().clone(true);
            var editorDiv = li.children(".editorDiv");
            if (editorDiv.children("#editor").length) {
                editorDiv.children("#editor").remove();
                editorDiv.children(".optionInput").show();
            }
            li.insertBefore(t.children().last());
            editorDiv.children(".optionInput").html("");
            optionsReorder(t.children("li.item"));

            //添加答案
            addAnswer(t);

            //绑定答案选择事件
            selectAnswer();
        }
    }
    else if (t.children("li.editorItem").length > 4) {
        for (var j = t.children("li.editorItem").length; j > 4; j--) {
            t.children("li.editorItem").eq(j - 1).remove();
            t.siblings(".right-xuanxiang").children(".xuanxiang-group").children("a").eq(j - 1).remove();
        }
    }
}

//清空编辑区域表单内容
function resetEditArea() {
    //删除重复的编辑器
    $(".edui-container").eq(1).remove();

    ume.setContent("<p></p>");
    $("#editor").hide();
    $("#editor").parents('.edui-container').hide();
    $("#tiganInfo").html("").show();
    $("#zhishidian").val("");
    //$(".option").find(".optionInput").html("");
    //var option = $(".option");
    $(".editorDiv .optionInput").html("").show();
    $("#jianda").html("");
    $('#singleFieldTags').children().not('li.tagit-new').remove();
    if (score) {
        score.val("0分");
    }


    //题型部分重新恢复至初始状态

    //重置选择题选项
    var t1 = $("#tab1 ul");
    var t2 = $("#tab2 ul");
    resetOptionItems(t1);
    resetOptionItems(t2);


    //重置填空题选项
    var t3Ul = $("#tab3 ul");
    var t3LiWithItemC = t3Ul.children("li.editorItem");
    var t3LiFirstClone = t3LiWithItemC.first().clone(false);
    t3LiFirstClone.children("input").val("");
    t3LiFirstClone.find("ul").html("").removeClass().addClass("tiankong_ul");
    t3LiFirstClone.insertBefore(t3Ul.find(".other-function4"));
    AddTagitEvent(t3LiFirstClone);

    t3LiWithItemC.remove();

    $("#UnCheckAnsSeqInput").attr("checked", false);
    $("#UnCheckAnsSeqInput").parents(".other-function4").hide();

    $("#allBlankScore").html(0);

    //重置判断题选项
    var t4 = $("#tab4 .xuanxiang-group a");
    t4.removeClass("selected");

    //设置试题类型
    var tx = $("#tixing");
    tx.children("ul").children("li").children("a").removeClass("selected").eq(0).addClass("selected");
    tx.siblings(".option").hide().eq(0).show();

    //解析试题重置
    $("#explanation-tab").show();
    $("#explanation").hide().find(".optionInput").html("");

    $("#allBlankScore").parent().hide();
    $("#forBlank label").html("分值");
}

//删除栏目、移动试题到新栏目
function deleteColumn() {
    $(".question-review .question-title .small-icon-left a.delete").unbind("click").click(function () {
        deleteTitle($(this).parent().parent(), false);
    })
}

//删除栏目、移动试题到新栏目 currentColumn为要删除的标题，identifier为true表示从试卷目录管理处删除，为false标识直接删除
function deleteTitle(currentColumn, identifier) {
    //当栏目下没有试题时，直接删除栏目。否则弹出对话框
    var thisTitle = currentColumn;
    var radioIndex = 0;

    //当大于一个章节的时候能被删除
    if ($(".question-review").length > 1) {

        //当章节栏目下没有试题
        if (thisTitle.siblings(".group-question").length == 0) {

            //询问框
            layer.confirm('栏目下面没有试题，是否删除栏目？', {
                btn: ['删除', '取消'] //按钮
            }, function () {
                //不为默认章节
                if (thisTitle.attr("data-sectionguid")) {
                    $.post(DomainUrlHelper.InstituCenterAction + "api/apipaper/removesection", {
                        sectionGuid: thisTitle.attr("data-sectionguid"),
                        examPaperGUID: paperGuid
                    }, function (data) {
                        consoleLog(data);
                        if (data.ErrorCode == "E0006") {
                            layer.msg('栏目已删除！', { icon: 1 });

                            //删除前需要移走试题编辑区
                            if (thisTitle.siblings().hasClass("editArea")) {
                                var qr = $(".question-review");
                                var index = qr.index(thisTitle.parent());

                                //当删除为最后一个时
                                if (index == qr.length - 1) {
                                    qr.eq(qr.length - 2).append(editArea);
                                }
                                else {
                                    qr.eq(qr.length - 1).append(editArea);
                                }
                                thisTitle.parent().remove();
                            }
                            else {
                                thisTitle.parent().remove();
                            }


                            if (identifier) {
                                layer.closeAll('page');
                                //试卷目录管理
                                catalogueManage();
                            }

                        }
                        else {
                            layer.msg('栏目删除失败！', { icon: 1 });
                        }
                        //刷新章节序号
                        updateSectionOrder();

                        //页面试题重新排序
                        questionsReorder();

                        //设置栏目的总分
                        setColumnScore();

                        //更新左侧目录
                        updateLeftCatalogue();

                        //初始化左侧目录拖动排序功能
                        initSortalbe();
                        // 调整章节样式
                        checkSection();
                    })
                }
                else {
                    layer.msg('栏目已删除！', { icon: 1 });
                    thisTitle.parent().remove();


                    if (identifier) {
                        layer.closeAll('page');
                        //试卷目录管理
                        catalogueManage();
                    }

                    //刷新章节序号
                    updateSectionOrder();

                    //页面试题重新排序
                    questionsReorder();

                    //设置栏目的总分
                    setColumnScore();

                    //更新左侧目录
                    updateLeftCatalogue();

                    //初始化左侧目录拖动排序功能
                    initSortalbe();
                    // 调整章节样式
                    checkSection();
                }

            }, function () { });
        }
            //当章节栏目下有试题
        else {

            if (identifier) {
                layer.closeAll();
            }
            //弹出框
            var layerControl = layer.open({
                type: 1,
                title: ["删除设置", "background-color: #ffc600; font-size: 18px; line-height: 42px; padding-left: 20px;"],
                skin: '', //加上边框 layui-layer-rim
                area: ['578px', '448px'], //宽高
                content: '<div id="deletePop">' +
                         '<div class="open-content">' +
                            '<div class="confirm-information">您是否要删除栏目?</div>' +
                            '<div class="item-list clearfix">' +
                                '<div class="input-block">' +
                                    '<input type="radio" name="delete-col" id="delete-all" checked="checked" >' +
                                '</div>' +
                                '<label for="delete-all">删除栏目及栏目下所有内容</label>' +
                            '</div>' +
                            '<div class="item-list clearfix">' +
                                '<div class="input-block">' +
                                    '<input type="radio" name="delete-col" id="delete-col" >' +
                                '</div>' +
                                '<label for="delete-col">只删除栏目</label>' +
                            '</div>' +
                            '<div id="move" style="display:none;">' +
                                '<div class="move">试题批量移动至</div>' +
                                '<select class="move-paper" disabled="disabled"></select>' +
                            '</div>' +
                        '</div>' +
                        '<div class="open-button">' +
                            '<div class="open-container clearfix"><a href="javascript:void(0)" class="cancel">取 消</a><a href="javascript:void(0)" class="save">删除</a></div>' +
                        '</div>' +
                      '</div>'
            });

            //设置删除弹出框的选项值
            var qTitle = $(".question-title");
            var index = qTitle.index(thisTitle); //获取当前标题的序号

            var select = $("#deletePop .open-content select.move-paper");
            var len = qTitle.length;


            if (len > 1) {
                for (var i = 0; i < len; i++) {
                    //非随机试题
                    if (examPaperForm == 1) {
                        if (i != index) {
                            var option = "<option value=" + qTitle.eq(i).attr("data-sectionguid") + " data-index=" + i + ">" + qTitle.eq(i).children(".question-title-content").text() + "</option>";
                            select.append(option);
                        }
                    }
                    //如果是随机试题
                    if (examPaperForm == 2) {
                        if (i != index && qTitle.eq(i).children(".question-title-content").children(".randomTx").text() == qTitle.eq(index).children(".question-title-content").children(".randomTx").text()) {
                            var option = "<option value=" + qTitle.eq(i).attr("data-sectionguid") + " data-index=" + i + ">" + qTitle.eq(i).children(".question-title-content").text() + "</option>";
                            select.append(option);
                        }
                    }
                }
            }



            //选择只删除章节，还是删除章节和下面的试题
            var deleteInput = $("#deletePop .open-content .item-list .input-block input");
            deleteInput.click(function () {
                radioIndex = deleteInput.index(this);
                if (radioIndex == 0) {
                    select.attr("disabled", true);
                    $("#move").hide();
                }
                if (radioIndex == 1) {
                    select.attr("disabled", false);
                    $("#move").show();
                }

            })

            //取消删除
            $("#deletePop .cancel").click(function () {
                layer.close(layerControl);
            })

            //保存修改
            $("#deletePop .save").click(function () {
                var loadingLayer = loadingAnimation();
                //删除章节以及下面的试题
                if (radioIndex == 0) {
                    $.post(DomainUrlHelper.InstituCenterAction + "api/apipaper/removesection", {
                        toSectionGUID: null,
                        sectionGuid: thisTitle.attr("data-sectionguid"),
                        examPaperGUID: paperGuid

                    }, function (data) {
                        consoleLog(data);
                        if (data.ErrorCode == "E0006") {

                            //删除前需要移走试题编辑区
                            if (thisTitle.siblings().hasClass("editArea")) {
                                var qr = $(".question-review");
                                var index = qr.index(thisTitle.parent());

                                //当删除为最后一个时
                                if (index == qr.length - 1) {
                                    qr.eq(qr.length - 2).append(editArea);
                                }
                                else {
                                    qr.eq(qr.length - 1).append(editArea);
                                }
                                thisTitle.parent().remove();
                            }
                            else {
                                thisTitle.parent().remove();
                            }

                            //刷新章节序号
                            updateSectionOrder();

                            //页面试题重新排序
                            questionsReorder();

                            //设置栏目的总分
                            setColumnScore();

                            //更新左侧目录
                            updateLeftCatalogue();

                            //初始化左侧目录拖动排序功能
                            initSortalbe();
                            // 调整章节样式
                            checkSection();

                            layer.close(layerControl);
                            layer.close(loadingLayer);

                            if (identifier) {
                                layer.closeAll('page');
                                //试卷目录管理
                                catalogueManage();
                            }
                        }
                    })
                }
                //删除章节，移动下面的试题
                if (radioIndex == 1) {
                    if (select.children().length > 0) {
                        $.post(DomainUrlHelper.InstituCenterAction + "api/apipaper/removesection", {
                            toSectionGUID: select.children("option:selected").attr("value"),
                            sectionGuid: thisTitle.attr("data-sectionguid"),
                            examPaperGUID: paperGuid

                        }, function (data) {
                            consoleLog(data);
                            if (data.ErrorCode == "E0006") {
                                var count = thisTitle.siblings(".group-question").length;
                                var dIndex = select.children("option:selected").attr("data-index");
                                var gqCollection = thisTitle.siblings(".group-question");
                                for (var i = 0; i < count; i++) {
                                    $(".question-review").eq(dIndex).append(gqCollection[i]);
                                }
                                thisTitle.parent().remove();

                                //刷新章节序号
                                updateSectionOrder();

                                //页面试题重新排序
                                questionsReorder();

                                //设置栏目的总分
                                setColumnScore();

                                //更新左侧目录
                                updateLeftCatalogue();

                                //初始化左侧目录拖动排序功能
                                initSortalbe();
                                // 调整章节样式
                                checkSection();

                                layer.close(layerControl);
                                layer.close(loadingLayer);
                                if (identifier) {
                                    layer.closeAll('page');
                                    //试卷目录管理
                                    catalogueManage();
                                }
                            }
                        })
                    }
                    else {
                        layer.close(loadingLayer);
                        layer.msg("没有相同题型的栏目可以移动！");
                    }

                }

                //if (identifier) {
                //    layer.closeAll('page');
                //    //试卷目录管理
                //    catalogueManage();
                //}
            })

        }
    }
        //当只剩下一个栏目时不能删除
    else {
        layer.msg('删除失败，至少应保留一个栏目！', { icon: 2 });
    }


}

//timer为每次递归的时间，offsetValue为每次递归的偏移量，两者都影响编辑器回到顶部的速度
var scrollTopFlag = -1;//判断递归
function scrollTopLoop_body(timer, offsetValue, marginToTop, targetValue) {

    if (document.body.scrollTop <= targetValue - marginToTop && document.body.scrollTop != scrollTopFlag) {
        setTimeout(function () {
            scrollTopFlag = document.body.scrollTop;
            document.body.scrollTop = document.body.scrollTop + offsetValue;
            scrollTopLoop_body(timer, offsetValue, marginToTop, targetValue);
        }, timer);
    }
    else {
        scrollTopFlag = -1;
    }
}

function scrollTopLoop_documentElement(timer, offsetValue, marginToTop, targetValue) {

    if (document.documentElement.scrollTop <= targetValue - marginToTop && document.documentElement.scrollTop != scrollTopFlag) {
        setTimeout(function () {
            scrollTopFlag = document.documentElement.scrollTop;
            document.documentElement.scrollTop = document.documentElement.scrollTop + offsetValue;
            scrollTopLoop_documentElement(timer, offsetValue, marginToTop, targetValue);
        }, timer);
    }
}

//将编辑区域移动到顶部
function moveEditAreaToTop() {
    editArea.show();

    var targetValue = $("#editArea").offset().top;
    var marginToTop = 150;
    var timer = 0;
    var offsetValue = 30;

    if (document.compatMode == "BackCompat") {
        //document.body.scrollTop = $("#editArea").offset().top - marginToTop;
        scrollTopLoop_body(timer, offsetValue, marginToTop, targetValue);
    }
    else { //document.compatMode == "CSS1Compat" 

        if (document.documentElement.scrollTop == 0 && document.body.scrollTop == 0) {

            try {
                //document.documentElement.scrollTop = $("#editArea").offset().top - marginToTop;
                scrollTopLoop_documentElement(timer, offsetValue, marginToTop, targetValue);
            } catch (e) {
                //document.body.scrollTop = $("#editArea").offset().top - marginToTop;
                scrollTopLoop_body(timer, offsetValue, marginToTop, targetValue);
            }

            try {
                //document.body.scrollTop = $("#editArea").offset().top - marginToTop;
                scrollTopLoop_body(timer, offsetValue, marginToTop, targetValue);
            } catch (e) {
                //document.documentElement.scrollTop = $("#editArea").offset().top - marginToTop;
                scrollTopLoop_documentElement(timer, offsetValue, marginToTop, targetValue);
            }

        }
        else {
            document.documentElement.scrollTop == 0 ? scrollTopLoop_body(timer, offsetValue, marginToTop, targetValue) : scrollTopLoop_documentElement(timer, offsetValue, marginToTop, targetValue);
        }
    }

}

//鼠标移动到选择题选项上背景和字体变色
function changeOptionQuestionStyle() {
    $(".question-list > .item").hover(function () {
        $(this).addClass("select-background").children("label").addClass("red-value");
    }, function () {
        $(this).removeClass("select-background").children("label").removeClass("red-value");
    })
}

//试题编辑栏的显隐
function toggleEditAreaBar() {
    $(".group-question").unbind("hover").hover(function () {
        $(this).find(".small-right-icon").show();
    }, function () {
        $(this).find(".small-right-icon").hide();
    })
}

//限制文字数目，str为需要限制的字符串，length为需要保留的字符长度，以英文字符为准
function cutString(str, length) {
    //获取字符串的实际长度，中文为2，英文数字为1
    var realLength = 0, len = str.length, charCode = -1, newStr = new String();
    for (var i = 0; i < len; i++) {
        charCode = str.charCodeAt(i);
        if (charCode >= 0 && charCode <= 128) {
            realLength += 1;
        }
        else {
            realLength += 2;
        }
        if (realLength <= length) {
            newStr = newStr.concat(str.charAt(i));
        }
    }
    if (realLength > length) {
        newStr = newStr + "...";
    }
    return newStr;
}

//设置栏目总分
function setColumnScore() {
    var column = $(".question-review");
    var pScore;
    for (var i = 0; i < column.length; i++) {
        pScore = 0;
        if (column.eq(i).children(".group-question").length > 0) {
            for (var j = 0; j < column.eq(i).children(".group-question").length; j++) {
                pScore += parseInt(column.eq(i).children(".group-question").eq(j).find(".score").html());
            }
        }
        column.eq(i).find(".sectionScore").html(pScore);
    }
}

//获取编辑器内容
function getUMEditorContent() {
    //替换其中的换行符
    var editContent = ume.getContent().replace("<br/>", "").replace("<p>", "").replace("</p>", "");
    //var editContent = ume.getContent().replace("<br/>", "");
    if (editContent.endWith("&nbsp;</p>") && !editContent.endWith(" &nbsp;</p>")) {
        editContent = editContent.substring(0, editContent.length - 10).concat("</p>");
    }
    while (editContent.endWith(" &nbsp;</p>")) {
        window.console && console.log("editContent.endWith&nbsp=" + editContent.endWith(" &nbsp;"));
        editContent = editContent.substring(0, editContent.length - 11).concat("</p>");
    }
    return editContent;
}

// 判断是否以“**”开头
String.prototype.startWith = function (str) {
    var reg = new RegExp("^" + str);
    return reg.test(this);
}

// 判断是否以“**”结尾
String.prototype.endWith = function (str) {
    var reg = new RegExp(str + "$");
    return reg.test(this);
}

// 跟据章节下试题条目数动态调整章节高度（解决章节标签下无试题情况）
function checkSection() {
    $.each($(".child-list"), function (m) {
        var childNumer = $(this).children(".child").length;
        if (childNumer == 0) {
            $(this).children('.nochild').remove();
            $(this).append(" <span class='nochild' style='margin-left: 50px; color: #b3b3b3;'>暂无试题</span>");
        } else {
            $(this).children('.nochild').remove();
        }

        //var childNumer = $(this).children(".child").length == 0 ? 1 : $(this).children(".child").length;
        //$(this).attr("style", "height:" + (childNumer * 44) + "px");
        //$(this).append(" <span>暂无试题</span>");
    })
}

// 验证是否是整数
function isNum(s) {
    //var regu = "^([0-9]*)$";
    var regu = "^([0-9]*[.0-9])$"; // 小数测试
    var re = new RegExp(regu);
    if (s.search(re) != -1)
        return true;
    else
        return false;
}

function validateNum(value) {
    var reg = new RegExp("^[0-9]*$");
    if (!reg.test(value)) {
        return false;
    }
    if (!/^[0-9]*$/.test(value)) {
        return false;
    }
    return true;
}

/**
 * 转半角字符
 */
function toSBC(str) {
    var result = "";
    var len = str.length;
    for (var i = 0; i < len; i++) {
        var cCode = str.charCodeAt(i);
        //全角与半角相差（除空格外）：65248（十进制）
        cCode = (cCode >= 0xFF01 && cCode <= 0xFF5E) ? (cCode - 65248) : cCode;
        //处理空格
        cCode = (cCode == 0x03000) ? 0x0020 : cCode;
        result += String.fromCharCode(cCode);
    }
    return result;
}

//转义  标签转为字符 
function htmlEncodeJQ(str) {
    return $('<span/>').text(str).html();
}

//反转义  字符串转为标签 
function htmlDecodeJQ(str) {
    return $('<span/>').html(str).text();
}

//判断是否含有特殊字符
function checkInput(str) {
    if (/[~!@#$%^&*()_+<>?:"{},.\/;'[\]]/im.test(str)) {
        return false;
    } else {
        return true;
    }
}

//返回字符串str字节长度  
function getByteLen(str) {
    var len = 0;
    for (var i = 0; i < str.length; i++) {
        if (str[i].match(/[^\x00-\xff]/ig) != null) //全角
            len += 2;
        else
            len += 1;
    }
    return len;
}
function AddTagitEvent(thisNode,isHavePlaceHolder) {
    var placeHolder=" 回车完成录入，可添加相似答案";
    if(isHavePlaceHolder==false){
        placeHolder=""
    }
    $(thisNode).tagit({
        availableTags: array,
        placeholderText: placeHolder,
        readOnly: false,
        allowSpaces: true,
        singleField: true,
        singleFieldNode: thisNode.children('input.tiankong_inputContent'),
        singleFieldDelimiter: '&@&',
        beforeTagAdded: function (event, ui) {
            if ($("#UnCheckAnsSeqInput").is(":checked")) {
                var allli = $("#tab3").find("li.tagit-choice");
                var result = true;
                allli.each(function () {
                    if ($(this).children("span").text() == ui.tagLabel) {
                        layer.msg("不检验顺序时，答案不能重复！");
                        result = false;                        
                    }
                });
                return result;
            }
            if (ui.tagLabel.length > 50) {
                layer.msg("单个空答案不能超过50个字符！");
                return false;
            }
        },
        afterTagAdded: function (event, ui) {
            if (event.target) {
                var inputTag = $(event.target).find("input.ui-autocomplete-input");
                if (inputTag) {
                    inputTag.attr("placeholder", "");
                }
            }
        },
        afterTagRemoved: function (event, ui) {
            CheckTiankongHaveRepeat();
            if (event.target) {
                var tags = $(event.target).find("li.tagit-choice");
                if (tags == null || tags.length == 0) {
                    var inputTag = $(event.target).find("input.ui-autocomplete-input");
                    if (inputTag) {
                        inputTag.attr("placeholder", " 回车完成录入，可添加相似答案");
                    }
                }               
            }
        }
    });
}
function UnCheckAnsSeqClick(abcd) {
    if ($(abcd).is(":checked")) {
        if (!CheckTiankongHaveRepeat()) {
            layer.msg("不检验顺序时，答案不能重复！")
            return false;
        }
    }
    else {
        var allli = $("#tab3").find("li.tagit-choice");
        allli.each(function () {
            $(this).removeClass("redBgc");
        });
    }
}

function CheckTiankongHaveRepeat() {
    if (index == 2) {
        var allli = $("#tab3").find("li.tagit-choice");
        allli.each(function () {
            $(this).removeClass("redBgc");
        });

        var sumAnswer = "";
        var isUnCheckAnsSeqInput = $("#UnCheckAnsSeqInput").is(":checked");
        var tAnswer = $("#tab3").find("input.tiankong_inputContent");
        if (tAnswer.length > 0) {
            for (var j = 0; j < tAnswer.length; j++) {
                if (isUnCheckAnsSeqInput) {
                    var thisAnswer = $.trim(tAnswer.eq(j).val());
                    if (thisAnswer) {
                        sumAnswer += thisAnswer + "&@&";
                    }
                }
            }
            if (sumAnswer != "" && isUnCheckAnsSeqInput) {
                var sumAnswerArray = sumAnswer.split("&@&");
                //得出重复的
                if (sumAnswerArray.length > 0) {

                    var repeatArray = sumAnswerArray.duplicate();
                    if (repeatArray && repeatArray.length > 0) {                       
                        for (var k = 0; k < repeatArray.length; k++) {
                            var thisAnswerOr = repeatArray[k];
                            if (thisAnswerOr) {
                                for (var l = 0; l < allli.length; l++) {
                                    var thisli = $(allli[l]);
                                    if (thisli.children("span").text() == thisAnswerOr)
                                    {
                                        thisli.addClass("redBgc");
                                    }
                                }                                            
                            }
                        }
                        return false;
                    }
                }
            }
        }        
    }
    return true;
}

Array.prototype.duplicate = function () {
    var ary = this.sort();//数组排序
    var cffwxmsAry = new Array();
    //所有重复元素添加进新数组内
    for (var i = 0; i < ary.length; i++) {
        if (ary[i] == ary[i + 1]) {
            cffwxmsAry.push(ary[i]);
        }
    }

    var result = [], isRepeated;
    //对重复元素数组进行元素去重
    for (var k = 0; k < cffwxmsAry.length; k++) {
        isRepeated = false;
        for (var j = 0; j < result.length; j++) {
            if (cffwxmsAry[k] == result[j]) {
                isRepeated = true; break;
            }
        }
        if (!isRepeated) {
            result.push(cffwxmsAry[k]);
        }
    }
    return result;
}


